Skip to content

Instantly share code, notes, and snippets.

@auser
Created February 17, 2010 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save auser/306277 to your computer and use it in GitHub Desktop.
Save auser/306277 to your computer and use it in GitHub Desktop.
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