利用该功能将它们插入我产生所需范围内:如何扭转阵列,同时通过while循环
first_index = 0
last_index = 3
ranges = []
while first_index != last_index
while last_index != 0
if first_index < last_index
ranges << (first_index..last_index)
end
last_index -= 1
end
first_index += 1
last_index = 3
end
p ranges
的输出是:
[0..3, 0..2, 0..1, 1..3, 1..2, 2..3]
我需要恢复嵌套while
的输出循环,完成后。因此,在这个例子中,我需要:
[0..3, 0..2, 0..1].reverse
[1..3, 1..2].reverse
[2..3].reverse (wouldn't make any different on this, though)
我会得到的输出是:
[0..1, 0..2, 0..3, 1..2, 1..3, 2..3]
我可以在该函数调用reverse
不知何故? last_index
可以是任何整数。我用3来缩短输出。
'(0..3).to_a.combination(2).map {| a,b | a..b}'以预期的顺序返回范围。 – Stefan
@Stefan这就是几秒钟内的一个很好的解决方案。如果你可以写一个简短的解释答案,我会接受它,也许这将有助于其他人,有一天.. –