From: Einar Jørgen Haraldseid Date: Sat, 16 Feb 2019 08:46:34 +0000 (+0100) Subject: randomness checker X-Git-Url: https://git.slaskete.net/einar-bin/commitdiff_plain/10f3be9e9f8022a1e98c40f29a83acca7e2560b3?ds=inline randomness checker --- diff --git a/randomness.sh b/randomness.sh new file mode 100755 index 0000000..47022f5 --- /dev/null +++ b/randomness.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Visualize how random the $RANDOM function is +# while demonstrating some neat array functions and things + +# Check for sane parameter +if [[ "${1}" -lt 50 ]]; then + echo "Please input integer higher than 50" + exit 1 +fi + +# Declare arrays +declare -A Count=() +declare -A Graph=() + +# Loop n times +for ((n=0;n<${1};n++)); do + # Assign random number, use modulo to reduce to desired range, add 1 to get rid of 0 + Rand=$(( ( RANDOM % 8 ) + 1 )) + # Our Count array needs to be increased + (( Count[${Rand}]++ )) + # And append a character to our graph + Graph[$Rand]+=█ +done + +# Find extremes +Max=${Count[1]} +for n in "${Count[@]}"; do + (( n > Max )) && Max=${n} +done + +Min=${Count[1]} +for n in "${Count[@]}"; do + (( n < Min )) && Min=${n} +done + +# Find mean +Mean=$(bc <<< "scale=2;${1}/${#Count[@]}") + +# Unset Graph array if we can't get it to fit on screen +MaxWidth=$(tput cols) +(( MaxWidth -= 10 )) + +if [[ "${Max}" -gt "${MaxWidth}" ]]; then + unset Graph +fi + +# Loop through the Count array, note the # which returns the size of the array for us +for ((n=1;n<=${#Count[@]};n++)); do + # printf to get some better formatting (space padding) + printf "%-3s %-5s %s\n" ${n} ${Count[$n]} ${Graph[$n]} +done +echo -e "\nMin: ${Min}, Max: ${Max}, Mean: ${Mean}" \ No newline at end of file