利用該功能將它們插入我產生所需範圍內:如何扭轉陣列,同時通過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這就是幾秒鐘內的一個很好的解決方案。如果你可以寫一個簡短的解釋答案,我會接受它,也許這將有助於其他人,有一天.. –