Ruby中的单行重复排列

时间:2022-11-02 22:32:26

i know how to create permutation using ruby:

我知道如何使用ruby创建排列:

x = [*1..6]
x.permutation.each { |y| p y }

that resulting:

结果:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 6, 5]
[1, 2, 3, 5, 4, 6]
[1, 2, 3, 5, 6, 4]
[1, 2, 3, 6, 4, 5]
...
[6, 5, 4, 3, 1, 2]
[6, 5, 4, 3, 2, 1]

is there any one liner code to generate repeated permutation, such as:

是否有任何一个班轮代码可以生成重复的排列,例如:

x = [1,2,3]
x.something.each { |y| p y }

that give result:

给出结果:

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

2 个解决方案

#1


10  

Try #repeated_permutation:

试试#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]]

#2


6  

I noticed your question asked for combinations but your example used repeated permutations. If you are really interested in generating actual combinations, then a quick and dirty way to do this is:

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

>> 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"]

#1


10  

Try #repeated_permutation:

试试#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]]

#2


6  

I noticed your question asked for combinations but your example used repeated permutations. If you are really interested in generating actual combinations, then a quick and dirty way to do this is:

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

>> 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"]