0

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

3 Answers 3

3

You could do:

a.select{|v| v == 1}.size

It's only one solution

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.