判断一个数组是否是无重复的组合
Find if an array is a combination without repetition
我有一个包含五个元素的数组:
source = [:a, :b, :c, :d, :e]
我可以得到一个元素,两个元素,最多五个元素的组合。
source.combination(1)
#=> #<Enumerator: ...>
source.combination(1).to_a
#=> [[:a], [:b], [:c], [:d], [:e]]
source.combination(2).to_a
#=> [[:a, :b],
# [:a, :c],
# [:a, :d],
# [:a, :e],
# [:b, :c],
# [:b, :d],
# [:b, :e],
# [:c, :d],
# [:c, :e],
# [:d, :e]]
source.combination(5).to_a
#=> [[:a, :b, :c, :d, :e]]
我有这些数组:
a1 = [:e, :c, :b]
a2 = [:e, :c, :e]
a3 = [:e, :b, :k]
第一个是三个元素的组合,第二个无效,因为它有重复的元素,第三个有一个无效的元素。为了得到它们,我可以这样做:
source.combination(a1.length).to_a.any? {|c| (c - a1).empty?}
#=> true
source.combination(a1.length).to_a.any? {|c| (c - a2).empty?}
#=> false
source.combination(a2.length).to_a.any? {|c| (c - a3).empty?}
#=> false
但我想知道是否可以在不使用应用于枚举器的 to_a
方法计算所有组合的情况下计算它。
如果我对你的问题理解正确,这个方法基本上检查源数组和子数组是否有公共元素,并且公共元素的大小应该等于子数组。您可以使用数组交集进行检查。
source = [:a, :b, :c, :d, :e]
a1 = [:e, :c, :b]
a2 = [:e, :c, :e]
a3 = [:e, :b, :k]
(source & a1).size == a1.size
=> true
(source & a2).size == a2.size
=> false
(source & a3).size == a3.size
=> false
我有一个包含五个元素的数组:
source = [:a, :b, :c, :d, :e]
我可以得到一个元素,两个元素,最多五个元素的组合。
source.combination(1)
#=> #<Enumerator: ...>
source.combination(1).to_a
#=> [[:a], [:b], [:c], [:d], [:e]]
source.combination(2).to_a
#=> [[:a, :b],
# [:a, :c],
# [:a, :d],
# [:a, :e],
# [:b, :c],
# [:b, :d],
# [:b, :e],
# [:c, :d],
# [:c, :e],
# [:d, :e]]
source.combination(5).to_a
#=> [[:a, :b, :c, :d, :e]]
我有这些数组:
a1 = [:e, :c, :b]
a2 = [:e, :c, :e]
a3 = [:e, :b, :k]
第一个是三个元素的组合,第二个无效,因为它有重复的元素,第三个有一个无效的元素。为了得到它们,我可以这样做:
source.combination(a1.length).to_a.any? {|c| (c - a1).empty?}
#=> true
source.combination(a1.length).to_a.any? {|c| (c - a2).empty?}
#=> false
source.combination(a2.length).to_a.any? {|c| (c - a3).empty?}
#=> false
但我想知道是否可以在不使用应用于枚举器的 to_a
方法计算所有组合的情况下计算它。
如果我对你的问题理解正确,这个方法基本上检查源数组和子数组是否有公共元素,并且公共元素的大小应该等于子数组。您可以使用数组交集进行检查。
source = [:a, :b, :c, :d, :e]
a1 = [:e, :c, :b]
a2 = [:e, :c, :e]
a3 = [:e, :b, :k]
(source & a1).size == a1.size
=> true
(source & a2).size == a2.size
=> false
(source & a3).size == a3.size
=> false