Is it possible to get the difference between two dynamic arrays regardless of their order?

If I have two arrays and I try to find their difference.

[1, 2, 3, 2, 6, 7] - [2, 1]

I get:

[3, 6, 7]

But if I flip these arrays around

[2, 1] - [1, 2, 3, 2, 6, 7]

I get:

[]

My question is that my two arrays are dynamic, I need to know if there is a difference between both arrays regardless of their order. What is the simplest expression to find?

+3
source share
2 answers

You can define it:

class Array
  def diff(o)
    (o - self) + (self - o)    # alternatively: (o + self) - (o & self)
  end
end

[2, 1].diff [1, 2, 3, 2, 6, 7] # [3, 6, 7]
[1, 2, 3, 2, 6, 7].diff [2, 1] # [3, 6, 7]
[2, 3, 3, 1].diff [2, 4, 5]    # [4, 5, 3, 3, 1]
[2, 4, 5].diff [2, 3, 3, 1]    # [3, 3, 1, 4, 5]

The correct answer probably depends on what you want at the end, though, as the two previous examples show.

If you need only unique values, you first need to convert the two inputs to the settings and return the result as an array:

class Array
  def diff(o)
    (o.to_set ^ to_set).to_a   # or simply (o.to_set ^ self).to_a
  end
end

[2, 4, 5].diff [2, 3, 3, 1]    # [4, 5, 3, 1]

(Perhaps there is also a built-in Rails method.)

+5

Set#^:

require 'set'

([2, 1].to_set ^ [1, 2, 3, 2, 6, 7]).to_a
# => [3, 6, 7]
([1, 2, 3, 2, 6, 7].to_set ^ [2, 1]).to_a
# => [3, 6, 7]

:

Set#^ , , .

+2

All Articles