Hotshot Hotshot - 5 days ago 5
Bash Question

Bash: Iterating through an array to get the value at each index

The main goal of this program is to simulate the drawing of a card as many times as the user chooses and then print out a histogram using '*' to represent the number of hits on each card. However, the problem that I am having is retrieving the elements in each array and printing the stars that correlates with them. This is what I have so far:

timelimit=5
echo -e "How many trials would you like to run? \c"
read -t $timelimit trials

if [ ! -z "$trials" ]
then
echo -e "\nWe will now run $trials trials"
else
trials=10
echo -e "\nWe will now run the default amount of trials: $trials"
fi

count=1
MAXCARD=53
declare -a CARDARRAY

while [ "$count" -le $trials ]
do
card=$RANDOM
let "card %= MAXCARD"
let "CARDARRAY[$card] += 1"
let "count += 1"
done
echo ${CARDARRAY[@]}

for (( i=0; i<${#CARDARRAY[@]}; i++));
do
#declare "temp"="${CARDARRAY[$i]}"
#echo "$temp"
#for (( j=0; j<temp; j++));
#do
#echo "*"
#done
echo "$i"
done


Obviously the last for loop is where I'm having trouble and is currently the latest attempt at printing the stars according to how many hits each card has.

Answer

You were pretty close. Here's how I'd paraphrase your script:

#!/bin/bash
timelimit=5
printf %s 'How many trials would you like to run? '
read -t $timelimit trials

if [[ ! -z $trials ]] ; then
    printf '\nWe will now run %d trials\n' $trials
else
    trials=10
    printf '\nWe will now run the default amount of trials: %d\n' $trials
fi

count=1
MAXCARD=53
declare -a CARDARRAY

while (( trials-- )) ; do
    (( CARDARRAY[RANDOM % MAXCARD] += 1 ))
done  

printf '%s\n' "${CARDARRAY[*]}"

for (( i=0; i<MAXCARD ; i++));
do
    printf %02d: $i

    for (( j=0 ; j<${CARDARRAY[i]:-0} ; j++ )) ; do
        printf %s '*'
    done
    printf '\n' ''
done

You can use set -xv to see what bash is running at each step.