patternrubyMinor
Creating a sorted hash counting the occurrences of a number in an array
Viewed 0 times
thecountingnumberoccurrencescreatingarrayhashsorted
Problem
I figured something like this:
This outputs:
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:
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.inject({}) { |h, el| h[el] = a.count(el) if h[el].nil? ; h }.sort_by {|k,v| v}.reverse.inject({}) { |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:
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]}]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.