Hello,
I am writing a script which expects as its input a hash with student names as the keys and marks as the values. The script then returns array of average marks for student scored 60-70, 70-80, and over 90.
Output expected
50-70 1
70-90 3
over 90 0
The test script so far I have written looks like this
#!/bin/bash
ARRAY=( "ABC:60"
"DEF:70"
"GHI:75"
"JKL:80" )
for student in "${ARRAY[@]}" ; do
KEY="${student%%:*}"
VALUE="${student##*:}"
printf "%s's marks is %s.\n" "$KEY" "$VALUE"
done
I am able to store the input as hash with keys and its values but not able to calculate the average and give the output as expected. Any suggestions would be appreciated.
The script posted and output don't show any average calculation. Grades range total maybe.
An ex.:
#!/bin/bash
ARRAY=( "ABC:60"
"DEF:70"
"GHI:75"
"JKL:80" )
declare -a scores=("1000-90" "90-80" "80-70" "70-60" "60-50" "50-0")
declare -a ranges=("over 90" "90-80" "80-70" "70-60" "60-50" "under 50")
declare -A totals
for student in "${ARRAY[@]}" ; do
KEY="${student%%:*}"
VALUE="${student##*:}"
printf "%s's marks is %s.\n" "$KEY" "$VALUE"
c=0;
for i in "${scores[@]}" ; do
if [[ $VALUE -ge ${i##*-} ]] && [[ $VALUE -le ${i%%-*} ]] ; then
(( totals[${ranges[$c]}] = totals[${ranges[$c]}] + 1 ))
fi
(( c = c + 1 ))
done
done
for s in "${ranges[@]}"
do
printf "%-10s %d\n" "$s" ${totals["$s"]}
done
This smells a bit like homework/coursework, but after a week here is another example:
#!/bin/bash
ARRAY=( "ABC:60"
"DEF:70"
"GHI:75"
"JKL:80" )
RANGES=( "-50" "50-70" "70-90" "90-" )
for student in "${ARRAY[@]}" ; do
KEY="${student%%:*}"
VALUE="${student##*:}"
printf "%s's marks is %s.\n" "$KEY" "$VALUE"
for ((cnt=0; cnt < ${#RANGES[@]}; cnt++)) ; do
leftr=${RANGES[cnt]%-*}
rightr=${RANGES[cnt]#*-}
[ -z "$leftr" ] && leftr=0
[ -z "$rightr" ] && rightr=999
if [ $VALUE -ge $leftr ] && [ $VALUE -lt $rightr ] ; then
((COUNTS[cnt]++))
fi
done
done
# note: COUNTS[] was not preset, so elements with 0 are missing
# but printf "%d" will cast "" to 0
for ((cnt=0; cnt < ${#RANGES[@]}; cnt++)) ; do
printf "%-10s %d\n" "${RANGES[cnt]}" "${COUNTS[cnt]}"
done
Output:
ABC's marks is 60.
DEF's marks is 70.
GHI's marks is 75.
JKL's marks is 80.
-50 0
50-70 1
70-90 3
90- 0