我的目的是从列表
填充一个数组:
list = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 12, 13, 15]
按以下顺序:
- 后面不跟增量值(加 1)的各个整数将直接添加到结果数组中。
- 后面跟着递增值(加 1)的整数将被添加到范围数组中,然后该数组将被添加到结果中,并再次重置以用于下一个范围。
正确的输出应该是:
solution(list)
# => [-6, [-3, -2, -1, 0, 1], [3, 4, 5], [7, 8, 9, 10], [12, 13], 15]
我的代码和输出如下。
def solution(list)
result = []
idx = 0
loop do
range = []
loop do
if list[idx+1] - list[idx] == 1
range << list[idx]
idx += 1
else
result << list[idx]
idx += 1
break
end
end
result << range
break if idx == list.size - 1
end
result
end
solution(list)
# => [-6, [], 1, [-3, -2, -1, 0], 5, [3, 4], 10, [7, 8, 9], 13, [12]]
代码不正确。你能告诉我我缺少什么吗?
最佳答案
您缺少 chunk_while
。
list.chunk_while{|a, b| a.next == b}.map{|a| a.one? ? a.first : a}
# => [-6, [-3, -2, -1, 0, 1], [3, 4, 5], [7, 8, 9, 10], [12, 13], 15]
关于arrays - 按相应范围对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44258881/