Skip to content

Instantly share code, notes, and snippets.

@charmcitygavin
Last active December 10, 2015 15:28
Show Gist options
  • Save charmcitygavin/4454519 to your computer and use it in GitHub Desktop.
Save charmcitygavin/4454519 to your computer and use it in GitHub Desktop.
This is as far as I've been able to get (so far) with the "Calculate the array mode" exercise in the DBC prep material. Am I on the right track? Am I making this too complicated on myself?
def mode(array)
# This sets up the hash, each new key defaulting to a value of 0
count = Hash.new(0)
# This iterates through the original array,
# increasing each number's hash value each time it appears in the array.
array.each do |number|
counter[number] += 1
end
high_count = count.values.max
mode = []
count.each do |k, v|
if v == high_count
mode << k
end
end
return mode
end
@danigro77
Copy link

not bad
you could try it in one iteration with an if-else statement

@charmcitygavin
Copy link
Author

Hmm... sounds like a good idea. I'll wrestle with it for a while!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment