Last active
December 14, 2015 07:48
-
-
Save Stephenitis/5052762 to your computer and use it in GitHub Desktop.
find the mode in a array?
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
solution #1 | |
array = [1, 1, 1, 2, 3] | |
#whats going on here?? | |
freq = array.inject(Hash.new(0)) { |h,v| h[v] += 1; h } | |
arr.sort_by { |v| freq[v] }.last | |
solution #2 | |
def mode(array) | |
count = Hash.new(0) | |
array.each { |element| count[element] += 1 } | |
#count how many times an element[s] appears the most | |
# element of the array => number of times element occured in an array | |
# ex. {5 => 2, 6 =>2, 7 =>1} | |
max = count.values.max | |
count.keep_if { |key, val| val == max} | |
# count is {5 => 2, 6 =>2} | |
count.keys #return an array of those elements | |
end | |
#p mode ([5,5,6,6,7}) | |
#alt | |
def mode(array) | |
array.group_by {|num| array.count(num)}.max.last.uniq | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment