OhN*_*oez 6 ruby combinations function permutation
条件
a + b + c = 100
a,b,c positive integers or 0
Run Code Online (Sandbox Code Playgroud)
期望的输出:
[
[0,0,100],
[0,1,99 ],
... # all other permutations
[99,1,0 ],
[100,0,0]
]
Run Code Online (Sandbox Code Playgroud)
Stackoverflow说我的帖子没有太多的上下文来解释代码部分.你同意吗?(这是填充文本以满足其要求)
tok*_*and 13
我写道:
(0..100).flat_map { |x| (0..100-x).map { |y| [x, y, 100-x-y] } }
#=> [[0, 0, 100], [0, 1, 99]], ..., [99, 1, 0], [100, 0, 0]]
Run Code Online (Sandbox Code Playgroud)
网站注释1:这是一个典型的例子,其中列表理解能够发光(如果某个地方存在某种情况,甚至更多).由于Ruby没有LC,我们必须进行典型的OOP转换:N-1 flat_map + 1 map.在Ruby中使用LC是很棒的(检查这个功能请求),Scala已经证明即使是纯OOP语言也能从这种语法糖中获益(尽管由于隐式可迭代协议/方法,我可以理解开发人员的预防).在一个支持它们的想象中的Ruby上你会写:
[[x, y, 100-x-y] for x in 0..100 for y in 0..100-x] # imaginary Ruby
Run Code Online (Sandbox Code Playgroud)
旁注2:想象一下,您更喜欢耗费较少内存的解决方案(您可能不需要整个阵列).使用Ruby 2.0的懒惰解决方案只需要添加几个[lazy][2]代理:
(0..100).lazy.flat_map { |x| (0..100-x).lazy.map { |y| [x, y, 100-x-y] } }
Run Code Online (Sandbox Code Playgroud)
旁注3:为了完整性,在@akuhn答案中,使用枚举器的另一个懒惰解决方案:
Enumerator.new do |e|
(0..100).each { |x| (0..100-x).each { |y| e.yield([x, y, 100-x-y]) } }
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
406 次 |
| 最近记录: |