I've been thinking about a following problem - there are two arrays, and I need to find elements not common for them both, for example:
a = [1,2,3,4]
b = [1,2,4]
And the expected answer is [3]
.
So far I've been doing it like this:
a.select { |elem| !b.include?(elem) }
But it gives me O(N ** 2)
time complexity. I'm sure it can be done faster ;)
Also, I've been thinking about getting it somehow like this (using some method opposite to &
which gives common elements of 2 arrays):
a !& b #=> doesn't work of course
Another way might be to add two arrays and find the unique element with some method similar to uniq
, so that:
[1,1,2,2,3,4,4].some_method #=> would return 3
(a-b) | (b-a) # => [3]
See ruby-doc.org/core-1.9.3/Array.html#method-i-2D and note that it's not commutative, i.e. in generala-b != b-a