Created
February 17, 2010 04:07
-
-
Save auser/306277 to your computer and use it in GitHub Desktop.
This file contains 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(arr=[]) | |
hsh = {} | |
max = 0 | |
arr.each do |item| | |
# store the item in the array if, making certain to set it to one, if it's not in there | |
hsh.has_key?(item) ? hsh[item] += 1 : hsh[item] = 1 | |
end | |
# sort the array | |
sorted_array = hsh.sort{|a,b| b[1]<=>a[1]} | |
# Get the max value | |
max = sorted_array[0][1] | |
mode_arry = [] | |
# Count the array up until it's at it's max | |
sorted_array.each do |arr| | |
mode_arry << arr[0] if arr[1] >= max | |
end | |
mode_arry | |
end | |
p mode %w(a b a a b c dd e e e) # ["e", "a"] | |
p mode %w(a b a a b c dd e e) # ["a"] | |
p mode %w(snowboarding is more than fun. super fun.) # ["fun."] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment