给定一个整数数组,例如:
array = [1,2,3,5,6,7,20,21,33,87,88,89,101]
该数组包含k
连续的子序列(在本例中k = 6
),例如“1,2,3”和“87,88,89”。如何获得包含这些k
子序列数组的数组?
对于上面的示例,这些将是:
[[1,2,3], [5,6,7], [20,21], [33], [87,88,89], [101]]
未移动0
的是一个假人。它可以是任何数字。
[1, 2, 3, 5, 6, 7]
.unshift(0)
.each_cons(2).slice_before{|m, n| m + 1 < n}.map{|a| a.map(&:last)}
# => [[1, 2, 3], [5, 6, 7]]
编辑:
如果您使用的是轨道,有一个简单的方法,使用主动支撑拆分方法
def sort_it(arr)
(arr.first..arr.last).to_a.split {|i| !arr.include?(i) }.select &:present?
end
或在红宝石中
def sort_it(arr)
tmp, main = [], []
arr.each_with_index do |x, i|
if arr[i-1]
if arr[i-1] + 1 == x
tmp << x
else
main << tmp unless tmp.empty?
tmp = [x]
end
else
tmp << x
end
end
main << tmp
main
end
> a = [1, 3, 5, 6, 8, 9, 11, 12, 13, 14, 16, 27]
> sort_it(a)
=> [[1], [3], [5, 6], [8, 9], [11, 12, 13, 14], [16], [27]]
def seq_sort(array)
finished = [array.first], i = 0
array.each_cons(2) do |(a,b)|
if b - a == 1
finished[i] << b
else
finished[i += 1] = [b]
end
end
finished
end
> seq_sort([1,2,38,39,92,94,103,104,105,1002])
=> [[1,2], [38, 39], [92], [94], [103, 104, 105], [1002]]