From: "Simon Kröger" Date: 2005-10-16T05:31:27+09:00 Subject: Re: How to get non-unique elements from an array? Robert Klemme wrote: > Sam Kong wrote: > >>> You don't need the exact number of repetitions. Try this: >>> a = [0,1,2,3,4,5,2,3] >>> h = {} >>> u = a.inject([]) {|res, x| h[x] ? res + [x] : h[x] = res} >> >> >> Thank you for the insight. >> >> However, your code doesn't work if an element repeats more than twice. >> >> a = [0,1,2,3,4,5,2,3,2] #there are three 2's. >> Your code's result is [2, 3, 2] instead of [2, 3] >> It should be modified like >> u = a.inject([]) {|res, x| h[x] ? res + [x] : h[x] = res}.uniq >> >> Other than that, I like your way. >> Thank you again. >> >> Sam > > >>> a = [0,1,2,3,4,5,2,3] > > => [0, 1, 2, 3, 4, 5, 2, 3] > >>> a.inject(Hash.new(0)) {|h,e| h[e]+=1;h}.select {|k,v|v>1}.map {|a,b|a} > > => [2, 3] > > Quite complicated... Yeah, some thoughts of mine: --------------------------------------------------------------------- require 'enumerator' a = [0,1,2,3,4,3,5,2,3] p a.sort.to_enum(:each_cons, 2).select{|i, j|i==j}.flatten.uniq p a.select{|x|a.index(x) != a.rindex(x)}.uniq p a.dup.reject{|x|a.delete(x)}.uniq --------------------------------------------------------------------- all have downsides (performance wise and the last one is destructive) cheers Simon