我想为名为Multiset的类创建不同的方法。
我有所有必需的方法,但我不确定如何编写交集,联合和子集方法。
对于intersection和union,我的代码就是这样开始的:
def intersect(var)
x = Multiset.new
end
以下是一个例子:
X = [1, 1, 2, 4]
Y = [1, 2, 2, 2]
然后X
和Y
的交集为[1, 2]
。
答案 0 :(得分:284)
我认为X
和Y
是数组?如果是这样,有一种非常简单的方法:
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]
答案 1 :(得分:128)
利用您可以通过&
(交集),-
(差异)和|
(联合)对数组进行集合操作这一事实。
显然我没有将MultiSet实现为规范,但这应该让你开始:
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]
答案 2 :(得分:2)
如果Multiset
来自Array
类
x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]
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]
x.difference(y) # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z) # => [4] (ONLY IN RUBY 2.6)
x - y # => [4, 7]
x & y # => [1, 2]
有关Ruby 2.6中新方法的更多信息,可以检查this blog post about its new features