HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Creating a sorted hash counting the occurrences of a number in an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thecountingnumberoccurrencescreatingarrayhashsorted

Problem

I figured something like this:

a= [1, 2, 3, 2, 2, 2, 3, 1, 1, 1, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a.inj­ect({}) { |h, el| h[el]­ = a.cou­nt(el) if h[el]­.nil? ; h }.sor­t_by {|k,v­| v}.re­verse.inje­ct({}) { |h, el| h[el[­0]] = el[1]­ ; h}


This outputs:

=> {0=>10, 4=>9, 2=>5, 1=>4, 3=>2}


But it seems like a clunky solution that does to many passes over the "same" thing.

What would be a good way to do this from different viewpoints?

I.e:

  • an "impress your Java friends" (small one-liner not used in production)



  • Performance



  • Easily read

Solution

Not sure which viewpoint this would be, but this is what I came up with:

Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}]


Update: I'm not thrilled with this, but this one sorts by the occurrence count, descending.

Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}.sort_by {|a| a[1]}.reverse]

Code Snippets

Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}]
Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}.sort_by {|a| a[1]}.reverse]

Context

StackExchange Code Review Q#26672, answer score: 2

Revisions (0)

No revisions yet.