user6589814 user6589814 - 17 days ago 5
Ruby Question

Find most duplicated numbers inside a array

I have the following array

[1, 2, 3, 4, 5, 1, 2, 5, 3, 4, 2, 3, 1, 3, 2, 2]`


I want to find out 2 things:

1) How many duplicates of each number is it?

For instance: 1, 3 times, 4, 2 times etc.

2) Find 3 most duplicated numbers in the
array
.

For instance:
[2, 3, 1]
since 2 is duplicated 5 times, 3 is duplicated 4 times & 1 is duplicated 3 times.

I have tried

arr = [1, 2, 3, 4, 5, 1, 2, 5, 3, 4, 2, 3, 1, 3, 2, 2]
= arr.group_by { |e| e }.map { |e| e[0] if e[1][1] }.compact


But results are not what I am looking for:
[1, 2, 3, 4, 5]

Answer

To get a count of duplicated entries per duplicate you can go with:

arr.group_by(&:itself)
   .each_with_object({}) {|(k, v), hash| hash[k] = v.size }
#=> {1=>3, 2=>5, 3=>4, 4=>2, 5=>2}

To get 3 most duplicated entries:

arr.group_by(&:itself)
   .sort_by { |_k, v| -v.size }
   .take(3)
   .map(&:first)
#=> [2, 3, 1]
Comments