使用此功能,我可以生成所需的范围:
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 :(得分: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]
但是,请注意文档说:(强调添加)
该实施使无法保证产生组合的订单。
所以你可能想要明确sort
结果:
a.combination(2).sort
#=> [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]
答案 1 :(得分: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