Skip to content

Instantly share code, notes, and snippets.

@abloom
Last active December 15, 2015 17:20
Show Gist options
  • Save abloom/5296134 to your computer and use it in GitHub Desktop.
Save abloom/5296134 to your computer and use it in GitHub Desktop.
def mode(array)
arrayfreq = array.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
max_hits = arrayfreq.values.sort.last
array.find_all{ |v| arrayfreq[v] == max_hits }
end
# starting with this
mode([1,2,2,2,3,3,4,5,5,5,5])
# after the first line of your mode function, arrayfreq looks like this:
{
1 => 1,
2 => 4,
3 => 2,
4 => 1,
5 => 4
}
@ScottGo
Copy link

ScottGo commented Apr 2, 2013

those two new lines deliver these errors

Error!

mode returns the correct mode when mode is unique

expected: [5] got: [5, 5](compared using ==)

Error!

mode returns the correct mode when mode is not unique

expected: [5, 6] got: [5, 5, 6, 6, 6, 5](compared using ==)

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