2017-04-05 54 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