Find Out Most Frequently Occurring Element in an Array

Here is the topic:

Try to find out the most frequently occurring element in an array.

Thinking in Ruby, I found a solution like following:

1
2
3
4
nums = [1, 2, 4, 3, 1, 4, 1, 1, 4]
num_hash = Hash[nums.uniq.map { |num| [num, nums.count(num)] }]
most_freq = nums.sort_by { |num| num_hash[num] }.last
# most_freq == 1

This solution get a hash table about the elements with times, and then sort the array by the times, after that, the last element in the array is the most frequently element.

This would work, but when I asked in Ruby-China, people gave more simple solutions.

1
2
#provided by gaicitadie
nums.group_by{|i|i}.sort_by{|i|-i[1].length}.first.first
1
2
#provided by hysios
nums.group_by {|i| i}.max_by {|k, v| v.count }[0]
1
2
#provided by sevk
nums.group_by{|i| nums.count(i)}.max[1][0]
1
2
#provided by sevk
nums.max_by{|x| nums.count(x) }

Amazing, think in different, you can find out more solutions.