如何在Ruby中获得交集,并集和数组子集? [英] How can I get the intersection, union, and subset of arrays in Ruby?

查看:171
本文介绍了如何在Ruby中获得交集,并集和数组子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为称为 Multiset 的类创建不同的方法.

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

这里是一个例子:

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

XY的交集为[1, 2].

推荐答案

利用您可以通过执行&(交集),-(差异)和|(联合)对数组进行设置操作这一事实).

Utilizing the fact that you can do set operations on arrays by doing &(intersection), -(difference), and |(union).

很明显,我没有实现MultiSet规范,但这应该可以帮助您入门:

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]

这篇关于如何在Ruby中获得交集,并集和数组子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆