【问题标题】:Ruby Combinations with array elementsRuby 与数组元素的组合
【发布时间】:2012-01-04 21:57:41
【问题描述】:

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

【问题讨论】:

标签: ruby arrays combinations


【解决方案1】:

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 1.8.6...这是我正在开发的 Google SketchUp 插件,因此升级 Ruby 不是一种选择。无论如何感谢您的回复!问候
【解决方案2】:

这些组合与 [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

【讨论】:

【解决方案3】:

或者在 ruby​​ 1.9 中

%w(a b c d e).combination(3).to_a

会给你所有尺寸 3 的组合。

【讨论】:

  • 同样的问题,我被 Ruby 1.8.6 卡住了...感谢您的回复!
猜你喜欢
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多