Skip to content

Instantly share code, notes, and snippets.

@jkaihsu
Created March 7, 2013 08:16
Show Gist options
  • Save jkaihsu/5106396 to your computer and use it in GitHub Desktop.
Save jkaihsu/5106396 to your computer and use it in GitHub Desktop.
Write a method mode which takes an Array of numbers as its input and returns an Array of the most frequent values. If there's only one most-frequent value, it returns a single-element Array. For example, mode([1,2,3,3]) # => [3] mode([4.5, 0, 0]) # => [0] mode([1.5, -1, 1, 1.5]) # => [1.5] mode([1,1,2,2]) # => [1,2] mode([1,2,3]) # => [1,2,3], b…
def mode(array)
mode = array.inject(Hash.new(0)) { |h,v| h[v] = h[v] + 1; h}
mode.select{ |h,v| v == mode.values.max }.keys
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment