# optimization - Julia相当于python Continuous_groups（）函数

function consecutive_groups(array)
groups = eltype(array)[]
j = 0
for i=1:length(array)-1
if array[i]+1 != array[i+1]
push!(groups, array[j+1:i])
j = i
end
end
push!(groups, array[j+1:end])
return groups
end

Thomas Jalabert

36
laborg 2020-01-31 21:41

function consecutive_groups_2(v)
n = length(v)
groups = Vector{Vector{eltype(v)}}()

i = j = 1
while i <= n && j <= n
j = i
while j < n  && v[j] + 1 == v[j + 1]
j += 1
end
push!(groups,v[i:j])
i = j + 1
end

return groups
end

julia> x = collect(1:100000);

julia> @btime consecutive_groups(x)
165.939 μs (4 allocations: 781.45 KiB)
1-element Array{Array{Int64,1},1}:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10  …  99991, 99992, 99993, 99994, 99995, 99996, 99997, 99998, 99999, 100000]

julia> @btime consecutive_groups_2(x)
114.830 μs (4 allocations: 781.45 KiB)
1-element Array{Array{Int64,1},1}:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10  …  99991, 99992, 99993, 99994, 99995, 99996, 99997, 99998, 99999, 100000]