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 hidden or 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]) |
Author
Author
I tried max.push(k) to create an array of the returned keys (of maximum value), but it still only puts them as integers onto successive lines. I tried v.to_s.split, but that didn't work either.
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).
I agree w/ @Ale1. did that help?
Author
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
As you instructed, I broke down the problem into these 2 final steps. I found the max values with "b.each do | k, v |", and was thus able to find the respective keys. I'm able to 'puts' of these keys onto successive lines.
I've been Googling for hours trying to find a way to convert puts outputs on successive lines (versus strings on the same line) into an array, but to no avail. I found .split, but that doesn't seem to work for successive lines.
Thanks so much.