This function (not thoroughly tested) should be more efficient as it avoids the second for loop nested in the first and takes advantage of recursion, which would be necessary anyway.
function hullify1(X)
XY = Vector{Interval{Float64}}()
push!(XY,first(X))
for y in X[2:end]
h=findfirst(e->!isempty(e ∩ y),XY)
if isnothing(h)
push!(XY,y)
else
XY[h]=hull(XY[h],y)
end
end
#println(XY)
XY==X && return XY
hullify1(XY)
end
Summary
julia> using IntervalArithmetic, BenchmarkTools
julia> X = [Interval(0.0, 0.1), Interval(1,2), Interval(0.1, 0.2), Interval(9,10), Interval(2,3), Interval(0.2, 0.3), Interval(10,11), Interval(2,3), Interval(9,10)];
julia> function hullify1(X)
XY = Vector{Interval{Float64}}()
push!(XY,first(X))
for y in X[2:end]
h=findfirst(e->!isempty(e ∩ y),XY)
if isnothing(h)
push!(XY,y)
else
XY[h]=hull(XY[h],y)
end
end
#println(XY)
XY==X && return XY
hullify1(XY)
end
hullify1 (generic function with 1 method)
julia> function hullify(X)
XY = Set{Interval{Float64}}()
for x in X
any(x .⊆ XY) && continue
for y in X
(x == y || isempty(x ∩ y)) && continue
x = hull(x, y)
end
push!(XY, x)
end
XY==X && return XY
hullify(XY)
end
hullify (generic function with 1 method)
julia> X = [Interval(0.0, 0.1), Interval(1,2), Interval(0.1, 0.2), Interval(9,10), Interval(2,3), Interval(0.2, 0.3), Interval(10,11), Interval(2,3), Interval(9,10)];
julia> @btime hullify(X)
1.610 μs (45 allocations: 3.31 KiB)
Set{Interval{Float64}} with 3 elements:
[0, 0.3]
[1, 3]
[9, 11]
julia> @btime hullify1(X)
371.717 ns (6 allocations: 704 bytes)
3-element Vector{Interval{Float64}}:
[0, 0.3]
[1, 3]
[9, 11]
In fact, the version that uses only one level of for loops is faster.
PS
Does anyone have any idea why the print on the REPL in the second case has those weird indentations?