find the mode of a list of numbers in ruby

To find the mode of a list of numbers, we first need to count the number of occurrences of each element in the list. We can use a hash to keep track of the frequency of each element. Once we have the frequency count, we can sort the hash by the frequency values and return the element with the highest frequency.

Here's the code that implements this algorithm:

main.rb
def mode(numbers)
  frequency = Hash.new(0)
  numbers.each { |n| frequency[n] += 1 }
  frequency = frequency.sort_by { |k, v| v }
  frequency.last.first
end
157 chars
7 lines

Let's go through this code step by step.

We define a function mode that takes an array of numbers as an argument.

We initialize a hash frequency with a default value of 0. This means that if we access a key that doesn't exist in the hash, it will return 0 instead of nil.

We iterate over the array of numbers and increment the frequency count for each element in the hash.

We sort the hash by frequency values using sort_by. The sort_by method takes a block that is used to determine the sorting order. In this case, we're using the frequency values as the sorting key.

We return the largest key in the hash, which corresponds to the element with the highest frequency.

Now we can call the mode function with an array of numbers and get the mode:

main.rb
numbers = [1, 2, 2, 3, 3, 3, 4]
puts mode(numbers) #=> 3
57 chars
3 lines

gistlibby LogSnag