find the kth most frequent element in an array in ruby

One solution to find the kth most frequent element in an array in Ruby is to use a combination of a hash and a sort.

Here's the code:

main.rb
def kth_most_frequent(arr, k)
  counter = Hash.new(0)
  arr.each { |e| counter[e] += 1 }
  sorted_arr = counter.sort_by { |k, v| -v }
  return sorted_arr[k-1][0]
end
166 chars
7 lines

The kth_most_frequent method takes in two arguments - the array (arr) and the integer k.

First, we create a new Hash called counter with a default value of 0. Then, we iterate through the array and increment the value of the hash corresponding to each element in the array.

Next, we sort the hash by the value (v) in descending order, so that the most frequent elements appear first.

Finally, we return the key ([0]) of the kth element in the sorted hash (subtracting 1 from k since arrays are 0-indexed).

Here's an example usage of the method:

main.rb
arr = [1, 2, 3, 1, 2, 1]
k = 2
puts kth_most_frequent(arr, k) # outputs 2
74 chars
4 lines

gistlibby LogSnag