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]]
Split array by consecutive sequences [closed]
题
Given an array of integer such as:
array = [1,2,3,5,6,7,20,21,33,87,88,89,101]
This array contains k
consecutive subsequences (in this case k = 6
), such as "1,2,3" and "87,88,89". How do I get an array containing arrays of these k
subsequences?
For the above example these would be:
[[1,2,3], [5,6,7], [20,21], [33], [87,88,89], [101]]
解决方案 3
其他提示
The unshifted 0
is a dummy. It could be any number.
[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]]
EDIT:
If you are using rails, there is an easy way, using the active support split method
def sort_it(arr)
(arr.first..arr.last).to_a.split {|i| !arr.include?(i) }.select &:present?
end
or in Ruby
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]]
不隶属于 StackOverflow