我有一个包含可用元素的数组和一个包含所需元素的数组。我想知道是否所有必需的元素都可用。
数组可能包含“重复项”。然后必须有尽可能多的可用元素。我对#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"