【发布时间】: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
【问题讨论】:
-
你有什么问题...?
-
您在寻找排列组合吗?您可以尝试使用数组索引。
-
@three 类数组有一个permutation method。
-
您在寻找电源组吗? stackoverflow.com/questions/8533336/…
-
@steenslag 是的,不记得它是否在数组中:)
标签: ruby arrays combinations