Skip to content

Instantly share code, notes, and snippets.

@mattdvhope
Last active December 20, 2015 03:49
Show Gist options
  • Save mattdvhope/6066483 to your computer and use it in GitHub Desktop.
Save mattdvhope/6066483 to your computer and use it in GitHub Desktop.
Calculating the array mode
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])
@mattdvhope
Copy link
Author

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.

@mattdvhope
Copy link
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.

@Ale1
Copy link

Ale1 commented Jul 24, 2013

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).

@keithtom
Copy link

I agree w/ @Ale1. did that help?

@mattdvhope
Copy link
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