Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of times an element occurs in an array

Tags:

arrays

ruby

count

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?

like image 930
Robertgold Avatar asked Nov 16 '25 09:11

Robertgold


2 Answers

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"
like image 174
falsetru Avatar answered Nov 18 '25 05:11

falsetru


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"
like image 24
Andrei Avatar answered Nov 18 '25 07:11

Andrei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!