How would I separate a vector into groups where the values are close?

julia> function splitgroups(v)
         start = firstindex(v)
         groups = typeof(v)[]
         for stop in [findall(diff(v) .> 10); lastindex(v)]
           push!(groups, @view(v[start:stop]))
           start = stop + 1
         end
         groups
       end
splitgroups (generic function with 1 method)

julia> splitgroups(v)
4-element Vector{Vector{Int64}}:
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 [24, 28, 32, 36, 40]
 [500, 510, 520, 530, 540, 550, 560]
 [1000, 1002, 1004, 1006, 1008, 1010, 1012, 1014, 1016, 1018, 1020]

This checks for places where the difference between numbers becomes greater than 10, and splits at those places.

It avoids allocating memory for the new vectors by using @view, so the original vector v will be changed if the contents of these change. If the original vector v also will still be used, and you want them to be independent of each other, you can remove the @view at the cost of some performance.

1 Like