How can I get the intersection, union, and subset of arrays in Ruby?
Utilizing the fact that you can do set operations on arrays by doing &
(intersection), -
(difference), and |
(union).
Obviously I didn't implement the MultiSet to spec, but this should get you started:
class MultiSet
attr_accessor :set
def initialize(set)
@set = set
end
# intersection
def &(other)
@set & other.set
end
# difference
def -(other)
@set - other.set
end
# union
def |(other)
@set | other.set
end
end
x = MultiSet.new([1,1,2,2,3,4,5,6])
y = MultiSet.new([1,3,5,6])
p x - y # [2,2,4]
p x & y # [1,3,5,6]
p x | y # [1,2,3,4,5,6]
I assume X
and Y
are arrays? If so, there's a very simple way to do this:
x = [1, 1, 2, 4]
y = [1, 2, 2, 2]
# intersection
x & y # => [1, 2]
# union
x | y # => [1, 2, 4]
# difference
x - y # => [4]
Source