Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting by frequency of occurrence in an array

Is there an efficient way of doing this. I have an array

a=[1,2,2,3,1,2]

I want to output the frequency of occurrence in an ascending order. Example

[[3,1],[1,2],[2,3]]

Here is my code in ruby.

b=a.group_by{|x| x}
out={}

b.each do |k,v|
    out[k]=v.size
end

out.sort_by{|k,v| v}
like image 735
vishal Avatar asked May 02 '12 10:05

vishal


3 Answers

a = [1,2,2,3,1,2]
a.each_with_object(Hash.new(0)){ |m,h| h[m] += 1 }.sort_by{ |k,v| v }
#=> [[3, 1], [1, 2], [2, 3]]
like image 89
megas Avatar answered Nov 15 '22 13:11

megas


Something like this:

x = a.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }.to_a.sort{|a, b| a[1] <=> b[1]}
like image 32
Matzi Avatar answered Nov 15 '22 12:11

Matzi


Are you trying to work out the algorithm or do you just want the job done? In the latter case, don't reinvent the wheel:

require 'facets'
[1, 2, 2, 3, 1, 2].frequency.sort_by(&:last)
# => [[3, 1], [1, 2], [2, 3]] 
like image 29
tokland Avatar answered Nov 15 '22 12:11

tokland