好的,我已经在互联网上搜索了答案,还在我的 ruby 程序员中搜索了几个小时,但我无法解决这个问题。我正在编写一个脚本,用于根据数组中的元素进行各种组合。
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"] 或 ["a","c","d"] 或 [ "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
最佳答案
Functional方法(需要 Ruby >= 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"],
#]
关于Ruby 与数组元素的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8734647/