如何使用Ruby中的循环输出所有可能的组合? [英] How to output all possible combinations using loops in Ruby?
问题描述
我刚刚开始学习编程,并试图编写一个输出所有可能组合的函数.到目前为止,我已经找到了所有可能的大小为2的组合,但是我不确定如何使代码保持开放状态以处理更大的组合.某种递归会有用吗?
I just started to learn programming and am trying to write a function that outputs all possible combinations. So far I've been able to find all possible combinations of size 2 but I'm not sure how to leave the code open ended to deal with combinations of larger sizes. Would some sort of recursion would be useful?
我知道我可以使用内置的组合方法,但是我只是想弄清楚如何从头开始编写它.任何建议将不胜感激.谢谢!
I know I could use the built in combination method but I'm just trying to figure out how to write it from scratch. Any advice would be much appreciated. Thanks!
def two_combos(input)
list = []
for index1 in (0...input.length)
for index2 in (0...input.length)
if input[index1] != input[index2]
if list.include?([input[index2],input[index1]])==false
list << [input[index1],input[index2]]
end
end
end
end
return list
end
two_combos(["A","B","C"])
#outputs
=> [["A", "B"], ["A", "C"], ["B", "C"]]
#Missing
["A","B","C"]
推荐答案
此实现类似于以二进制形式递归计数:
This implementation is like counting recursively in binary:
def combinations(items)
return [] unless items.any?
prefix = items[0]
suffixes = combinations(items[1..-1])
[[prefix]] + suffixes + suffixes.map {|item| [prefix] + item }
end
> combinations(%w(a b c))
=> [["a"], ["b"], ["c"], ["b", "c"], ["a", "b"], ["a", "c"], ["a", "b", "c"]]
在每个阶段,这些组合都是以下内容的串联:
At each stage, the combinations are a concatenation of:
- 第一个元素
- 以下元素(元素1..n-1)的组合
- 第一个元素与以下元素的组合
这篇关于如何使用Ruby中的循环输出所有可能的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!