Last active
August 29, 2015 13:57
-
-
Save jvans1/9798262 to your computer and use it in GitHub Desktop.
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) | |
#Hash.new is good here because the 0 is default for blank values | |
hash = Hash.new(0) | |
#Just use an array literal | |
max = [] | |
array.each {|x| hash[x] += 1 } | |
hash.select do |key, value| | |
#i wouldn't name block local variables the same as other locals it can get confusing | |
hash[key].to_i == array[x].to_i | |
hash.values | |
end | |
end | |
def mode(array) | |
hash = Hash.new(0) | |
grouped_hash = array. | |
reduce(hash) do |hash, value| | |
hash[value] += 1 | |
hash | |
end | |
max_occurence = grouped_hash.values.max | |
grouped_hash.select{ |k, v| v == max_occurence }.keys | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment