Last active
December 18, 2015 22:59
-
-
Save tarynsauer/5858128 to your computer and use it in GitHub Desktop.
Exercise: Calculating the array mode
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(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