Ruby 与数组元素的组合

标签 ruby arrays combinations

好的,我已经在互联网上搜索了答案,还在我的 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/

相关文章:

c# - 如何在 Ruby 应用程序中匹配 C# 中 Unicode 字符串的 MD5 散列输出?

ios - 从 User * 分配给 NSArray * 的不兼容指针类型

android - 为什么它只显示来自 json 数组的最新数据

JavaScript 数组层次结构

ruby-on-rails - 无法启动 Rails 服务器 - 找不到 JavaScript 运行时

java - jodconverter 找不到 officeHome,在 centOS 5 中使用 docsplit

ruby - irb 使用 rbenv 加载错误的 ruby​​ 和 gem 路径

haskell - 从 Prolog 到 Haskell 的思考——生成真值组合列表

r - 创建二进制向量的组合

python - 查找具有给定总和的数字列表的所有组合