【问题标题】:How to reverse arrays while inserting them via the while loop如何在通过while循环插入数组时反转数组
【发布时间】:2017-08-31 07:54:09
【问题描述】:

通过这个函数,我可以生成所需的范围:

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 嗯,这在短短几秒钟内就是一个很好的解决方案。如果您可以写一个带有简短解释的答案,我会接受它,也许有一天这也会对其他人有所帮助..

标签: arrays ruby while-loop reverse


【解决方案1】:

所以我会得到输出:

=> [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]

但是,请注意文档中说:(已添加重点)

实现不保证产生组合的顺序

所以你可能想明确地sort 结果:

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

【讨论】:

  • ... 和排序 does 工作,因为Arrays 保证按字典顺序进行比较。 (我认为Array#&lt;=&gt; 的文档中提到了它。)
【解决方案2】:

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

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...3).flat_map { |a| (a+1..3).map { |b| a..b } } 0first_index3last_index
猜你喜欢
  • 2019-04-19
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 2013-04-01
  • 2016-06-07
  • 2018-06-06
  • 2018-10-12
  • 2018-10-16
相关资源
最近更新 更多