Counting the distinct elements in an array

2019-02-26 11:18发布

问题:

I have an array:

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

I want to display each unique element value and its associated element count like this:

1: 2
2: 1
3: 2
6: 1
8: 1
9: 1

So far I have:

a.sort.group_by { |x| x }
{
  1 => [
    [0] 1,
    [1] 1
  ],
  2 => [
    [0] 2
  ],
  3 => [
    [0] 3,
    [1] 3
  ],
  6 => [
    [0] 6
  ],
  8 => [
    [0] 8
  ],
  9 => [
    [0] 9
  ]
}

So each element of the Hash contains an array. I can use that array's count to get my answer, but I'm having trouble figuring out how to process the hash concisely.

Is this a horrible implementation?

a.sort.group_by { |x| x }.each {|x| puts "#{x[0]} #{x[1].count}" }

回答1:

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} 


回答2:

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


回答3:

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}


回答4:

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}