Re: Search for duplicate elements in the array
On 16 , 15:32, Robert Klemme <shortcut...@googlemail.com> wrote:
> This is way inefficient. You rather want a counter per element stored
> in a Map (HashMap or TreeMap in Java).
>
> dups = Hash.new 0
> arr.each {|x| dups[x]+=1}
> puts dups.select {|k,v| v>1}
>
> You can have it on one line if you prefer:
>
> puts arr.inject(Hash.new(0)) {|d,x| d[x]+=1; d}.select {|k,v| v>1}
>
> Kind regards
>
> robert
Thanks a lot! This is a new level of programing knowledge for me.
I'll try to make something like this with HashMap in Java.
|