Count the number of times an element occurs in the array
I have an Array that has elements [50, 20, 20, 5, 2]
called coins_used
.
I need to count and then output the number of times the coin appears in the array. using the output coin_used x frequency
.
Is there anyway that I can count the number of times an element occurs in the array, the output should be something like this:
50x1,20x2,5x1,2x1
What's the easiest way to do this?
source to share
By using Array#uniq
, you can get unique array elements. And Array#count
will return the number of elements found in the array.
By joining the mapped array with ,
, you can get what you want:
a = [50,20,20,5,2]
a.uniq.map { |x| "#{x}x#{a.count(x)}" }.join(',')
# => "50x1,20x2,5x1,2x1"
UPDATE More efficient version using Hash
for counting.
a = [50,20,20,5,2]
freq = Hash.new(0)
a.each { |x| freq[x] += 1 }
freq.map{ |key, value| "#{key}x#{value}" }.join(',')
# => "50x1,20x2,5x1,2x1"
source to share
ruby stdlib should really include a method like this (it's in mine .pryrc
, I use it daily)
module Enumerable
def count_by(&block)
each_with_object(Hash.new(0)) do |elem, memo|
value = block.call(elem)
memo[value] += 1
end
end
end
You use it like this:
[50, 20, 20, 5, 2].count_by{|e| e} # => {50=>1, 20=>2, 5=>1, 2=>1}
# ruby 2.2
[50, 20, 20, 5, 2].count_by(&:itself) # => {50=>1, 20=>2, 5=>1, 2=>1}
Converting this hash to a string of the desired format is up to you :)
source to share