好的,我在互联网上搜索了答案,并在我的红宝石程序员中搜索了几个小时,但我无法解决这个问题。我正在编写一个脚本,用于从数组中的元素中进行各种组合。
ar = ["a","b","c","d"]
此时我可以制作这些组合:
["a"],["a","b"],["a","b","c"],["a","b","c","d"],["b"],["b","c"],["b","c","d"],["c"],["c","d"],["d"]
这没关系,但我找不到搜索这些组合的方法,例如["a","c"] or ["a","c","d"] or ["a","d"]
等......
现在我的代码如下:
def combinaties(array)
combinaties = []
i=0
while i <= array.length-1
combinaties << array[i]
unless i == array.length-1
array[(i+1)..(array.length-1)].each{|volgend_element|
combinaties<<(combinaties.last.dup<<volgend_element)
}
end
i+=1
end
end
答案 0 :(得分:9)
Functional方法(需要Ruby&gt; = 1.9)来创建数组的powerset(除了你似乎不需要的空元素):
xs = ["a", "b", "c", "d"]
yss = 1.upto(xs.size).flat_map do |n|
xs.combination(n).to_a
end
#[
# ["a"], ["b"], ["c"], ["d"],
# ["a", "b"], ["a", "c"], ["a", "d"], ["b", "c"], ["b", "d"], ["c", "d"],
# ["a", "b", "c"], ["a", "b", "d"], ["a", "c", "d"], ["b", "c", "d"],
# ["a", "b", "c", "d"],
#]
答案 1 :(得分:4)
这些组合与[1 ..(2 ^ m - 1)]中的数字之间存在微不足道的对应关系(双射)(m是数组长度)。
考虑这样的数字n。它的二进制表示有m位数(包括前导零)。 1的数字位置是相应组合中元素的索引。
代码如下:
def combinations(array)
m = array.length
(1...2**m).map do | n |
(0...m).select { | i | n[i] == 1 }.map { | i | array[i] }
end
end
答案 2 :(得分:2)
或者在红宝石1.9中
%w(a b c d e).combination(3).to_a
将为您提供尺寸为3的所有组合。