#!/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}"