Ruby组合与数组元素

Ken*_*Gey 1 ruby arrays combinations

好吧,我在互联网上搜索了答案,并在我的红宝石程序员中搜索了几个小时,但我无法对此进行排序.我正在编写一个脚本,用于从数组中的元素中进行各种组合.

ar = ["a","b","c","d"]
Run Code Online (Sandbox Code Playgroud)

在这一点上,我能够做出这些组合:

["a"],["a","b"],["a","b","c"],["a","b","c","d"],["b"],["b","c"],["b","c","d"],["c"],["c","d"],["d"]
Run Code Online (Sandbox Code Playgroud)

这没关系,但我找不到搜索这些组合的方法,例如["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
Run Code Online (Sandbox Code Playgroud)

tok*_*and 9

功能方法(需要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"],
#]
Run Code Online (Sandbox Code Playgroud)