我知道如何创建一组值的排列.例如:
[*1..3].permutation(2)
Run Code Online (Sandbox Code Playgroud)
这导致以下六种排列:
[1, 2]
[1, 3]
[2, 1]
[2, 3]
[3, 1]
[3, 2]
Run Code Online (Sandbox Code Playgroud)
但是这个结果缺少三个排列,它们是相同值的组合,即:
[1, 1]
[2, 2]
[3, 3]
Run Code Online (Sandbox Code Playgroud)
如何获得所有排列,包括上面的重复排列?
Chr*_*ald 12
[*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]]
Run Code Online (Sandbox Code Playgroud)
我注意到你的问题要求组合,但你的例子使用了重复的排列.如果您真的对生成实际组合感兴趣,那么快速而肮脏的方法是:
>> 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"]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2315 次 |
| 最近记录: |