Skip to content

Instantly share code, notes, and snippets.

@tarynsauer
Last active December 18, 2015 22:59
Show Gist options
  • Save tarynsauer/5858128 to your computer and use it in GitHub Desktop.
Save tarynsauer/5858128 to your computer and use it in GitHub Desktop.
Exercise: Calculating the array mode
def mode(array)
freq = []
modes = []
max_array = []
array.each do |i|
freq << array.count(i)
end
# Combining array and frequencies into a hash
hash = Hash[array.zip(freq.map)]
# Should get max value (frequency) of hash
max_freq_key = hash.max_by { |k, v| v }[0]
max_freq = hash[max_freq_key]
hash.each do |key, value|
if value == max_freq
max_array << key
end
end
max_array
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment