I have an Array which has the elements [50, 20, 20, 5, 2], called coins_used.
I need to count and then output the number of times a coin occurs in the Array. using the output of coin_used x frequency.
Is there anyway that I can count the number of times an element occurs in the array, the output needs to be exactly like this:
50x1,20x2,5x1,2x1
How would be the easiest way to do this?
Using Array#uniq, you can get unique elements of the array. And Array#count will return the number of items 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 that use Hash to count.
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"
With Ruby >= 2.7 you can do:
coins_used = [50, 20, 20, 5, 2]
tally = coins_used.tally
tally.map { |k,v| "#{k}x#{v}" }.join(',')
=> "50x1,20x2,5x1,2x1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With