如何在通过 while 循环插入数组时反转数组

How to reverse arrays while inserting them via the while loop

使用这个函数我生成了需要的范围:

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 只是为了缩短输出。

So the output I would get:

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

这正是 Array#combination returns:

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]

但是,请注意文档说:(强调)

The implementation makes no guarantees about the order in which the combinations are yielded.

因此您可能想要明确 sort 结果:

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

如果顺序很重要,您可以使用中间数组。

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