Sort by frequency of occurrence in an array

Is there an effective way to do this. I have an array

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

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

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

Here is my ruby ​​code.

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

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

out.sort_by{|k,v| v}
+5
source share
5 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]]
+15
source

Something like that:

x = a.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }.to_a.sort{|a, b| a[1] <=> b[1]}
+7
source

Are you trying to develop an algorithm or just want to complete a task? In the latter case, do not reinvent the wheel:

require 'facets'
[1, 2, 2, 3, 1, 2].frequency.sort_by(&:last)
# => [[3, 1], [1, 2], [2, 3]] 
+5
source

use hashing, create a hash, go through the array, for each number in the array, update the hash count. it takes linear time O (n), and spatial complexity will be equal to storing the hash O (n).

+2
source
def frequency(a)
  a.group_by do |e|
    e
  end.map do |key, values|
    [key, values.size]
  end
end

a = [1, 2, 2, 3, 1, 2]
p frequency(a).sort_by(&:last)
+1
source

All Articles