Last active
December 20, 2015 09:19
-
-
Save MrBean83/6106708 to your computer and use it in GitHub Desktop.
"Calculating the array mode"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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