2017-04-05 50 views
2

利用該功能將它們插入我產生所需範圍內:如何扭轉陣列,同時通過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來縮短輸出。

+4

'(0..3).to_a.combination(2).map {| a,b | a..b}'以預期的順序返回範圍。 – Stefan

+1

@Stefan這就是幾秒鐘內的一個很好的解決方案。如果你可以寫一個簡短的解釋答案,我會接受它,也許這將有助於其他人,有一天.. –

回答

7

所以輸出我會得到:

=> [0..1, 0..2, 0..3, 1..2, 1..3, 2..3] 

這正是Array#combination回報:

a = [0, 1, 2, 3] 
a.combination(2).to_a 
#=> [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]] 

要獲取範圍:

a.combination(2).map { |a, b| a..b } 
#=> [0..1, 0..2, 0..3, 1..2, 1..3, 2..3] 

但是,請注意該文件umentation說:(強調)

的實施,使得沒有關於該組合產生的順序保證。

所以,你可能需要明確sort結果:

a.combination(2).sort 
#=> [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]] 
+2

...和排序*做*工作,因爲'陣列'保證按字典順序進行比較。 (我認爲它在'Array#<=>'的文檔中提到過。) –

1

如果訂單是至關重要的,你可以使用一箇中介陣列。

first_index = 0 
last_index = 3 
ranges = [] 
sub_ranges = [] 

while first_index != last_index 
    while last_index != 0 
     if first_index < last_index 
      sub_ranges << (first_index..last_index) 
     end 
      last_index -= 1 
    end 
    ranges << sub_ranges.reverse 
    sub_ranges = [] 
    first_index += 1 
    last_index = 3 
end 
ranges.flatten! 
p ranges 

這是一個很遠的鏡頭,但是對於大量的陣列操作變得相對昂貴。你可以更多地依賴數值工作。或者,您只需要這一個:

first_index = 0 
last_index = 3 
ranges = [] 

y = first_index + 1 

while first_index != last_index 
    while y <= last_index 
     ranges << (first_index..y) 
     y += 1 
    end 
    first_index += 1 
    y = first_index + 1 
end 
+0

一個更習慣的實現:'(0 ... 3).flat_map {| a | (a + 1..3).map {| b | a..b}}',其中'0'爲'first_index','3'爲'last_index' – Stefan