Well, until someone catches the horrible gaff on my last try by solving
the EXACT OPPOSITE PROBLEM WHILE BEING CONDESCENDING (my wife is used
to this), I'll keep trying:
Of course, the following is what works, finding duplicates ELEMENTS:
a.sort.to_s.scan(/(.)(\1)+/).flatten.uniq
Yeah... I guess it's clear this finds individual duplicate ELEMENTS,
not numbers. Works on single digits/letters/etc, blows up on all else.
How's that for useless?
What would do the trick is a 'non-greedy' array subtraction:
Normal(greedy): [0,1,2,3,4,5,2,3] - [0,1,2,3,4,5] =
Non-greedy: [0,1,2,3,4,5,2,3] - [0,1,2,3,4,5] = [2,3]
Seems like there has got to be a way of solving this w/o counters or
blocks...
Sam Kong wrote:
···
Hello!
I need to get non-unique elements from an array.
The best I came up with was using a hash as a counter for each unique
elements.
a = [0,1,2,3,4,5,2,3]
#What I want to get is [2,3] as 2,3 are non-unique elements.
h = {}
a.each do |i|
if h[i]
h[i] += 1
else
h[i] = 1
end
end
u =
h.each do |k, v|
if v > 1
u << k
end
end
#now u == [2,3]
This works fine.
But I think there's a better way.
How do you handle such a case?
Thanks in advance.
Sam