From: Robert Klemme Date: 2005-10-17T02:11:56+09:00 Subject: Re: How to get non-unique elements from an array? Ara.T.Howard wrote: > On Sun, 16 Oct 2005, Robert Klemme wrote: > >> para.hsu@gmail.com wrote: >>> Hello! >>> >>> How about this ? >>> (0...a.length-1).select{|i| a[i]==a[i+1]}.map{|i|a[i]}.uniq >> >> a needs to be sorted for this to work. As far as I remember that >> was not a guaranteed precondition so you would have to add that here. >> >> IMHO most efficient variants are still those that use a hash for >> element counting. > > and you needed even count i think: > > harp:~ > cat a.rb > class Array > def dups > h, d = {}, []; each{|e| h[e] ? (d << h.delete(e)) : (h[e] = e) > }; d end > end > > a = 0, 1, 2, 3, 4, 5, 2, 3, 2 > > p a.dups > > > harp:~ > ruby a.rb > [2, 3] Did you mean to provide this as an example that you actually need to count? Because that's what it is: ?> a = 0, 1, 2, 3, 4, 5, 2, 3, 2, 2 => [0, 1, 2, 3, 4, 5, 2, 3, 2, 2] >> ?> p a.dups [2, 3, 2] => nil >> Here's another alternative with limited counting: >> a = 0, 1, 2, 3, 4, 5, 2, 3, 2, 2 => [0, 1, 2, 3, 4, 5, 2, 3, 2, 2] >> a.inject({}) do |h,i| ?> case h[i] >> when nil >> h[i] = 1 >> when 1 >> h[i] = 2 >> when 2 >> # ok ?> else ?> raise "Error" >> end >> h >> end.inject([]) {|ar,(k,v)| ar << k if v == 2; ar} => [2, 3] I doubt though that performance is better than that with counting. Kind regards robert