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}

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]]

Something like this:

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

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]] 

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


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)

Need Your Help

How do I convert a height of an element given in vh to pixels?

javascript css css3 height viewport-units

I have the max-height of an element as 65vh. I need to convert it to pixels in my JavaScript to see whether an image can fit there or if I need to shrink/crop it. (am doing win8 App development).

Android Kernel Drivers for Camera Device

android camera kernel drivers decoder

I have a problem interfacing a video decoder(tvp5150) as a camera to a android samsung dev-kit works on FIMC API.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.