Skip to content

Instantly share code, notes, and snippets.

@Stephenitis
Last active December 14, 2015 07:48
Show Gist options
  • Save Stephenitis/5052762 to your computer and use it in GitHub Desktop.
Save Stephenitis/5052762 to your computer and use it in GitHub Desktop.
find the mode in a array?
solution #1
array = [1, 1, 1, 2, 3]
#whats going on here??
freq = array.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
arr.sort_by { |v| freq[v] }.last
solution #2
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