Counting the distinct elements in an array

不羁岁月 提交于 2019-12-02 00:25:53

How about:

a.inject({}) { |a,e| a[e] = (a[e] || 0) + 1; a }
 => {1=>2, 2=>1, 3=>2, 6=>1, 8=>1, 9=>1}

For example:

h = a.inject({}) { |a,e| a[e] = (a[e] || 0) + 1; a }
 => {1=>2, 2=>1, 3=>2, 6=>1, 8=>1, 9=>1} 
h.keys.sort.each { |k| puts "#{k}: #{h[k]}" }
1: 2
2: 1
3: 2
6: 1
8: 1
9: 1

From comments of others below:

a.each_with_object(Hash.new(0)) { |e,a| a[e] += 1 }
 => {1=>2, 2=>1, 3=>2, 6=>1, 8=>1, 9=>1} 

Use uniq to get the unique array values and sort to sort them in ascending order. Then for each of these values x, display a.count(x).

a = [1, 2, 3, 3, 6, 8, 1, 9]
a.uniq.sort.each {|x| puts '%d: %d' % [x, a.count(x)] }

For greater efficiency, make a hash that maps a value to the number of times it appears in the array. An easy way to do this is to initialize a Hash object that maps keys to zero by default. Then you can increment each value's count by one as you iterate through the array.

counts = Hash.new(0)
a.each {|x| counts[x] += 1 }
counts.keys.sort.each {|x| puts '%d: %d' % [x, counts[x]] }

Consider this:

a = [1, 2, 3, 3, 6, 8, 1, 9]

a.group_by{ |n| n } # => {1=>[1, 1], 2=>[2], 3=>[3, 3], 6=>[6], 8=>[8], 9=>[9]}
a.group_by{ |n| n }.map{ |k, v| [k, v.size ] } # => [[1, 2], [2, 1], [3, 2], [6, 1], [8, 1], [9, 1]]

Finally:

a.group_by{ |n| n }.map{ |k, v| [k, v.size ] }.to_h # => {1=>2, 2=>1, 3=>2, 6=>1, 8=>1, 9=>1}

Try this

module Enumerable
  def freq
    hash = Hash.new(0)
    each { |each| hash[each] += 1 }
    hash
  end
end

And then

[1, 2, 3, 3, 6, 8, 1, 9].freq
# => {1=>2, 2=>1, 3=>2, 6=>1, 8=>1, 9=>1} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!