5

我知道如何创建值数组的排列。例如:

[*1..3].permutation(2)

这导致以下六个排列:

[1, 2]
[1, 3]
[2, 1]
[2, 3]
[3, 1]
[3, 2]

但是这个结果缺少三个排列,它们是相同值的组合,即:

[1, 1]
[2, 2]
[3, 3]

我怎样才能得到所有的排列,包括上面重复的排列?

4

2 回答 2

12

尝试#repeated_permutation

[*1..3].repeated_permutation(3).to_a

 > pp [*1..3].repeated_permutation(3).to_a
[[1, 1, 1],
 [1, 1, 2],
 [1, 1, 3],
 [1, 2, 1],
 [1, 2, 2],
 [1, 2, 3],
 [1, 3, 1],
 [1, 3, 2],
 [1, 3, 3],
 [2, 1, 1],
 [2, 1, 2],
 [2, 1, 3],
 [2, 2, 1],
 [2, 2, 2],
 [2, 2, 3],
 [2, 3, 1],
 [2, 3, 2],
 [2, 3, 3],
 [3, 1, 1],
 [3, 1, 2],
 [3, 1, 3],
 [3, 2, 1],
 [3, 2, 2],
 [3, 2, 3],
 [3, 3, 1],
 [3, 3, 2],
 [3, 3, 3]]
于 2012-10-01T05:45:07.993 回答
6

我注意到您的问题要求组合,但您的示例使用了重复排列。如果您真的对生成实际组合感兴趣,那么一种快速而肮脏的方法是:

>> x = [* ?a..?c]
=> ["a", "b", "c"]
>> (0..x.length).each{|i| x.combination(i){|y| p y}}
[]
["a"]
["b"]
["c"]
["a", "b"]
["a", "c"]
["b", "c"]
["a", "b", "c"]
于 2012-10-01T05:56:56.843 回答