Skip to content

Instantly share code, notes, and snippets.

@kmandreza
Created January 2, 2013 03:30
Show Gist options
  • Save kmandreza/4431891 to your computer and use it in GitHub Desktop.
Save kmandreza/4431891 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)
count = Hash.new(0)
array.each { |element| count[element] += 1 } #count how many times an element[s] appears the most
# element of the array => number of times element occured in an array
# ex. {5 => 2, 6 =>2, 7 =>1}
max = count.values.max
count.keep_if { |key, val| val == max}
# count is {5 => 2, 6 =>2}
count.keys #return an array of those elements
end
#p mode ([5,5,6,6,7})
#alt
def mode(array)
array.group_by {|num| array.count(num)}.max.last.uniq
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment