How can I get the intersection, union, and subset of arrays in Ruby?

RubyUnionIntersectionSubset

Ruby Problem Overview


I want to create different methods for a class called Multiset.

I have all the required methods, but I'm unsure of how to write intersection, union, and subset methods.

For intersection and union, my code starts like this:

def intersect(var)
  x = Multiset.new
end

Here is an example:

X = [1, 1, 2, 4]
Y = [1, 2, 2, 2]

then the intersection of X and Y is [1, 2].

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - 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]

Solution 3 - Ruby

If Multiset extends from the Array class

x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]

UNION

x.union(y)           # => [1, 2, 4, 7]      (ONLY IN RUBY 2.6)
x.union(y, z)        # => [1, 2, 4, 7, 3]   (ONLY IN RUBY 2.6)
x | y                # => [1, 2, 4, 7]

DIFFERENCE

x.difference(y)      # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z)   # => [4] (ONLY IN RUBY 2.6)
x - y                # => [4, 7]

INTERSECTION

x.intersection(y)    # => [1, 2] (ONLY IN RUBY 2.7)
x & y                # => [1, 2]

For more info about the new methods in Ruby 2.6, you can check this blog post about its new features

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser487743View Question on Stackoverflow
Solution 1 - RubyJon GauthierView Answer on Stackoverflow
Solution 2 - RubyMike LewisView Answer on Stackoverflow
Solution 3 - RubyAna María Martínez GómezView Answer on Stackoverflow