Last active
December 20, 2015 03:49
-
-
Save mattdvhope/6066483 to your computer and use it in GitHub Desktop.
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) | |
# I created a new hash to make keys out each integer. | |
b = Hash.new(0) | |
# Here, I count/tabulate each time a particular integer appears. | |
array.each do |value| | |
b[value] = b[value] + 1 | |
end | |
# b returns {-2=>1, 1=>3, 2=>3, -5=>2, 3=>1, 4=>1} with the first array | |
# b returns {18=>1, 2=>2, -5=>4, 3=>2, 10=>1} with the second array | |
max = [] | |
b.each do |k, v| #e[key,value] | |
max.push(k) if v == b.values.max | |
end | |
max | |
end | |
# In its present form, it returns the keys 1, 2 for the first array and -5 for the second array, but I can't convert them into an array. | |
puts mode([1,2,4,-5,3,-2,1,1,-5,2,2]) | |
puts | |
puts mode([-5,2,-5,3,-5,3,18,-5,2,10]) |
I agree w/ @Ale1. did that help?
I had it all the time! I guess I should have actually tested it on the exercises!! :-o Thanks so much for your help!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
matt, your method output is already in array form. you are seeing it on your screen as integers in successive lines because you are using "puts" in lines 21-23. (not sure if that was what you were trying to fix).