Arrays 如何在通过while循环插入阵列时反转阵列
使用此函数,我生成所需的范围:Arrays 如何在通过while循环插入阵列时反转阵列,arrays,ruby,while-loop,reverse,Arrays,Ruby,While Loop,Reverse,使用此函数,我生成所需的范围: 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
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
我需要在嵌套的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..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]
但是,请注意,文档中说:(强调添加)
该实现不保证产生组合的顺序
因此,您可能希望显式显示结果:
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
第一个索引=0
最后的指数=3
范围=[]
子_范围=[]
而第一个_索引!=末日指数
而上一个_索引!=0
如果第一个索引<最后一个索引
sub_ranges(0..3).to_a.组合(2).map{a,b|a..b}
按预期顺序返回范围。@Stefan嗯,这是一个很好的解决方案,只需几秒钟。如果你能写一个简单解释的答案,我会接受的,也许有一天这也会对其他人有所帮助……而且排序确实有效,因为Array
s保证可以按字典顺序进行比较。(我认为在文档中提到了数组#
)一个更惯用的实现:(0…3).平面图{A |(A+1..3).映射{b | A..b}
,其中0
是第一个索引
而3
是最后一个索引
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