Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the most frequently occurring number in a bash array

Tags:

bash

I needed to find the most frequent number in an array. I did it this way:

# our array, the most frequent value is 55
declare -a array=(44 55 55 55 66 66)

# counting unque string with uniq and then sorting as numbers
array=($(printf "%s\n" "${array[@]}"| uniq -c | sort -n -r))

# printing 2nd element of array, as the first one - number of occurencies
printf ${array[1]}

Is it a better/more beautiful way to do it, instead of building a weird array(2nd step) which consists mixed counts and numbers together?

And am I doing sorting correctly? (uniq returns values in 2 columns, so I'm not sure how it chooses the column)

like image 789
Eugene Avatar asked Jan 24 '26 10:01

Eugene


1 Answers

If I had to do this in bash, I would use awk to skip sorting anything and just count the elements:

printf '%s\n' "${array[@]}" | awk '{
     if (++arr[$0] > max) {
       max=arr[$0];
       ans=$0
     }
   } 
   END {print ans}'

You can also implement the same algorithm in bash 4 or later using an associative array:

# These don't strictly need to be initialized, but it's safer
# to ensure they don't already have values.
declare -A counts=()
max=0
ans=
for i in "${array[@]}"; do
  if ((++counts[$i] > max)); then
    max=${counts[$i]}
    ans=$i
  fi
done
printf '%s\n' "$ans"
like image 99
chepner Avatar answered Jan 27 '26 01:01

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!