1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense, coming from a language like C and Java, the formatting of bash is very new! Thank you for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.