The simplest way is to use an Associative Array and the post-increment operator to increment a count of each number in your analog
indexed array, e.g.
#!/bin/bash
analog=(889 890 884 880 889 889 884 885 890 890)
declare -A frequent
for i in ${analog[@]}; do
((frequent[$i]++))
done
for i in "${!frequent[@]}"; do
printf "%s\t%s\n" "$i ==> ${frequent[$i]}"
done
Example Use/Output
$ bash ~/scr/array/freqarray.sh
880 ==> 1
884 ==> 2
885 ==> 1
889 ==> 3
890 ==> 3
You can simply keep a max
count as you iterate the associative array and output the key
associated with the max
frequent value (you have to determine how you handle the ties, e.g. 889, 890
are both 3
.)
Identifying the values with the maximum occurrences in analog, you could add maxkey
and maxval
variables as you loop over the occurrences and then a final loop similar to:
declare -i maxkey=0 maxval=0
for i in "${!frequent[@]}"; do
printf "%s\t%s\n" "$i ==> ${frequent[$i]}"
if (( ${frequent[$i]} > maxval )); then
maxval=${frequent[$i]}
maxkey=$i
fi
done
printf "\nmaximum occurences in analog:\n\n"
for i in "${!frequent[@]}"; do
if (( ${frequent[$i]} == maxval)); then
printf "%s\t%s\n" "$i ==> ${frequent[$i]}"
fi
done
Which would then produce the following output:
Example Use/Output
$ bash ~/scr/array/freqarray.sh
880 ==> 1
884 ==> 2
885 ==> 1
889 ==> 3
890 ==> 3
maximum occurences in analog:
889 ==> 3
890 ==> 3
Per Your Edit to Find Highest Value with Maximum Occurrence
To find the highest value with the maximum occurrence, you can simply add an additional check in your second loop and set the maxkey
value to the highest value in frequent
that has the maxval
. For example you can rearrange your final loop and add the output as follows:
printf "\nmaximum occurences in analog:\n\n"
for i in "${!frequent[@]}"; do
if (( ${frequent[$i]} == maxval)); then
printf "%s\t%s\n" "$i ==> ${frequent[$i]}"
(( i > maxkey)) && maxkey=i
fi
done
printf "\nhighest value with maximum occurrence:\n\n"
printf "%d\n" $maxkey
Example Use/Output
$ bash ~/scr/array/freqarray.sh
880 ==> 1
884 ==> 2
885 ==> 1
889 ==> 3
890 ==> 3
maximum occurences in analog:
889 ==> 3
890 ==> 3
highest value with maximum occurrence:
890