ruby subset

真子集和子集举例

子集比真子集范围大,子集里可以有全集本身,真子集里没有,还有,要注意非空真子集与真子集的区别,前者不包括空集,后者可以有。

比如全集I为{1,2,3},

它的子集为{1}、{2}、{3}、{1,2}、{1,3}、{2,3}、{1,2,3}、再加个空集;

而真子集为{1}、{2}、{3}、{1,2}、{1,3}、{2,3}、再加个空集,不包括全集I本身。

非空真子集为{1}、{2}、{3}、{1,2}、{1,3}、{2,3},不包括全集I及空集。

设全集I的个数为n,它的子集个数为2的n次方,真子集的个数为2的n次方-1,非空真子集的个数为2的n次方-2。

Add subset and superset operator for Array
 
 
 
class Array
 
  def subset?(other)
    self.each  do |x|
      if !(other.include? x)
        return false
      end
    end
    true
  end
 
  def superset?(other)
    other.subset?(self)
  end
 
end
 
a = [1234]
b = [23]
c = [2345]
 
flag1 = c.subset? a     # false
flag2 = b.subset? a     # true
flag3 = c.superset? b   # true
 
 

require "set"

a=[1,2,3]

as=a.to_set

b=[1,2]

bs=b.to_set

bs.subset?(as)=>true

原文地址:https://www.cnblogs.com/lexus/p/1909928.html