how do we count idential values on after appending value in to array
such that
a=[]
a<<1 count of 1 is 1
a<<1 count of 1 is 2
thanks
how do we count idential values on after appending value in to array
such that
a=[]
a<<1 count of 1 is 1
a<<1 count of 1 is 2
thanks
Someone will probably come up with a more specialized solution, but I would just reduce it
counts = [1,3,3].reduce({}) do |acc,n|
acc.tap do |a|
a[n] ||= 0
a[n] += 1
end
end
counts.each {|k,v| puts "#{k} was found #{v} times"}
(note that tap is ruby 1.9, and is backported in activesupport)
output of that will be
1 was found 1 times
3 was found 2 times
a = [1,2,3,4,5,1,2,2,3,4]
=> [1, 2, 3, 4, 5, 1, 2, 2, 3, 4]
a.uniq.each do |i|
?> puts i.to_s + ' has appeared ' + a.count(i).to_s + ' times'
end
1 has appeared 2 times
2 has appeared 3 times
3 has appeared 2 times
4 has appeared 2 times
5 has appeared 1 times
=> [1, 2, 3, 4, 5]