2

In ruby you can intersect two arrays using the & operator.
I'm trying to obtain the remainder of the intersection.

If I use a simple case - is sufficient:

array_1 = [0, 1]
array_2 = [0]
array_1 - array_2 => [1]

Now imagine we have 0 appearing multiple times in the first array

array_1 = [0, 0, 1]
array_2 = [0]
array_1 - array_2 => [1]

I would like to know the easiest way to obtain the difference between the first array and the intersection of the first array and the second array

array_1 = [0, 0, 1]
array_2 = [0]
array_1 ??? array_2 => [0, 1]
David B.
  • 788
  • 1
  • 11
  • 21
  • 1
    I think [this](https://stackoverflow.com/a/46244293/9785060) is what you're looking for. – Viktor May 19 '18 at 11:36
  • Actually, "opposite of intersection" is misleading. I understand it as a request for "complement of AND", and that would be so-called symmetric difference, or XOR in short. Check here for a quick example how to calculate it for arrays stackoverflow.com/a/4198470/717732 . However, keep in mind that XOR is very simple and may not fully handle duplicate items in either array. If you don't mean XOR, please think of some better way of naming your request than "opposite of &" because it's really confusing. – quetzalcoatl May 20 '18 at 07:16
  • For example, if Cary's answer suits your needs, then I'd consider calling your goal something along "removing specific items from array".. – quetzalcoatl May 20 '18 at 07:17

1 Answers1

2

I have proposed the method I think you want be added to the Ruby core. See the link for examples of its use.

class Array
  def difference(other)
    h = other.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }
    reject { |e| h[e] > 0 && h[e] -= 1 }
  end
end

a = [1,2,3,4,3,2,2,4] 
b = [2,3,4,4,4]

a.difference b
  #=> [1, 3, 2, 2] 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100