[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Making a count of unique elements in an array

Dan Kohn

1/9/2006 6:47:00 AM

Given an array, I need to produce a two-dimensional resulting array
where each pair consists of a unique element from the original array
and the number of times that element appears.

I found two ways to do this. Is one of them better? Is there a better
way?

arr = %w{a b b c c d e e e}
p arr
p arr.uniq.map {|e| [e, (arr.select {|ee| ee == e}).size ]}
counter = {}
arr.each {|e| counter[e] += 1 rescue counter[e] = 1 }
p counter.to_a


outputs:

["a", "b", "b", "c", "c", "d", "e", "e", "e"]
[["a", 1], ["b", 2], ["c", 2], ["d", 1], ["e", 3]]
[["a", 1], ["b", 2], ["c", 2], ["d", 1], ["e", 3]]

1 Answer

Robert Klemme

1/9/2006 10:08:00 AM

0

Dan Kohn wrote:
> Given an array, I need to produce a two-dimensional resulting array
> where each pair consists of a unique element from the original array
> and the number of times that element appears.
>
> I found two ways to do this. Is one of them better? Is there a
> better way?
>
> arr = %w{a b b c c d e e e}
> p arr
> p arr.uniq.map {|e| [e, (arr.select {|ee| ee == e}).size ]}
> counter = {}
> arr.each {|e| counter[e] += 1 rescue counter[e] = 1 }
> p counter.to_a
>
>
> outputs:
>
> ["a", "b", "b", "c", "c", "d", "e", "e", "e"]
> [["a", 1], ["b", 2], ["c", 2], ["d", 1], ["e", 3]]
> [["a", 1], ["b", 2], ["c", 2], ["d", 1], ["e", 3]]

I like #inject 1-liners:

>> arr = %w{a b b c c d e e e}
=> ["a", "b", "b", "c", "c", "d", "e", "e", "e"]
>> arr.inject(Hash.new(0)) {|h,x| h[x]+=1;h}
=> {"a"=>1, "b"=>2, "c"=>2, "d"=>1, "e"=>3}
>> arr.inject(Hash.new(0)) {|h,x| h[x]+=1;h}.to_a
=> [["a", 1], ["b", 2], ["c", 2], ["d", 1], ["e", 3]]
>> arr.inject(Hash.new(0)) {|h,x| h[x]+=1;h}.sort
=> [["a", 1], ["b", 2], ["c", 2], ["d", 1], ["e", 3]]

:-)

Kind regards

robert