确定数组是否经常包含另一个数组的所有元素?

时间:2013-07-23 18:44:45

标签: ruby

我有一个包含可用元素的数组和一个包含所需元素的数组。我想知道是否所有必需元素都可用。

数组可能包含“重复”。然后必须有尽可能多的元素可用。我第一次尝试#contains?方法失败,因为包括?只检查 如果元素至少可用一次

- 编辑:简化示例代码 -

# a first and simple trial
# that fails on duplicate elements
class Array
  def contains?(other)
    other.all? { |element| include?(element) }      
  end      
end

available = [1, 1, 1, 2, 2, 3]
small = [1, 1, 2, 3]  
big = [1, 1, 2, 3, 3] 

available.contains?(small) # is true as intended
available.contains?(big)   # is true but should be false
                           # because "big" contains more "3s" than "available"

1 个答案:

答案 0 :(得分:2)

def contains?(other)
  other.elements.group_by{|e| e}.all?{|e, a| elements.count(e) >= a.length}
end