我有一个array = [1, 3, 5, 1, 2, 3, 6, 7, 8, 9]
我需要提取不间断的范围,所以在这个例子中,[1, 2, 3]和[6, 7, 8, 9]。
请分享你的想法,但也请-修复我的时间循环以及。学习是我的首要任务。
我的主要尝试是至少得到一个范围:
$sequence = []
while array.length > 0 do
p @compare1 = array.index(0)
p @compare2 = array.index(1)
if @compare1 + 1 == @compare2
$sequence << @compare1
end
array = array[1..-1]
end 但不管用..。
发布于 2017-04-04 12:34:53
不错的解决方案:
array.chunk_while { |i, j| i + 1 == j }.select { |range| range.size > 1 }
=> [[1, 2, 3], [6, 7, 8, 9]] 在您的代码中,问题在于您要求的是值0(而不是0)和1的索引,而不是0和1位置的值。这是我注意到的第一个问题。你可以
compare1 = array[0]
compare2 = array[1]https://stackoverflow.com/questions/43207200
复制相似问题