Skip to content

Instantly share code, notes, and snippets.

@MrBean83
Last active December 20, 2015 09:19
Show Gist options
  • Save MrBean83/6106708 to your computer and use it in GitHub Desktop.
Save MrBean83/6106708 to your computer and use it in GitHub Desktop.
"Calculating the array mode"
def mode(array)
array.group_by do |e|
e
end.values.max_by(&:size).first
end
---------------------------------
def mode(array)
array.inject(Hash.new(0)){ |h,i| h[i] += 1; h }.max{ |a,b| a[1] <=> b[1] }.first
end
---------------------------------
def mode(array)
array.group_by{|a| a }.sort_by{|a,b| b.size<=>a.size}.first[0]
end
@MrBean83
Copy link
Author

SOLUTION:

def mode(array)
box = Hash.new(0)
popular = []
array.each { |value| box[value] += 1 }
box.each { |key, value| popular.push(key) if value == box.values.max }
popular
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment