Patchet, bruker nyere API-er
[einar-bin] / randomness.sh
1 #!/bin/bash
2 # Visualize how random the $RANDOM function is
3 # while demonstrating some neat array functions and things
4
5 # Check for sane parameter
6 if [[ "${1}" -lt 50 ]]; then
7 echo "Please input integer higher than 50"
8 exit 1
9 fi
10
11 # Declare arrays
12 declare -A Count=()
13 declare -A Graph=()
14
15 # Loop n times
16 for ((n=0;n<${1};n++)); do
17 # Assign random number, use modulo to reduce to desired range, add 1 to get rid of 0
18 Rand=$(( ( RANDOM % 8 ) + 1 ))
19 # Our Count array needs to be increased
20 (( Count[${Rand}]++ ))
21 # And append a character to our graph
22 Graph[$Rand]+=
23 done
24
25 # Find extremes
26 Max=${Count[1]}
27 for n in "${Count[@]}"; do
28 (( n > Max )) && Max=${n}
29 done
30
31 Min=${Count[1]}
32 for n in "${Count[@]}"; do
33 (( n < Min )) && Min=${n}
34 done
35
36 # Find mean
37 Mean=$(bc <<< "scale=2;${1}/${#Count[@]}")
38
39 # Unset Graph array if we can't get it to fit on screen
40 MaxWidth=$(tput cols)
41 (( MaxWidth -= 10 ))
42
43 if [[ "${Max}" -gt "${MaxWidth}" ]]; then
44 unset Graph
45 fi
46
47 # Loop through the Count array, note the # which returns the size of the array for us
48 for ((n=1;n<=${#Count[@]};n++)); do
49 # printf to get some better formatting (space padding)
50 printf "%-3s %-5s %s\n" ${n} ${Count[$n]} ${Graph[$n]}
51 done
52 echo -e "\nMin: ${Min}, Max: ${Max}, Mean: ${Mean}"