Skip to content

Commit fbb9c67

Browse files
committed
optimize allocations as MST has always n-1 connections where n is the number of nodes
1 parent 10f94b1 commit fbb9c67

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

src/mst.jl

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,15 +178,19 @@ function solve(problem::MstProblem)::MstResult
178178

179179
assigned = Set{Int64}()
180180
unassigned = nodes(conns)
181-
connresult = Connection[]
181+
182+
n = length(unassigned)
183+
184+
# In MST, there must be n-1 connections for n nodes
185+
connresult = Vector{Connection}(undef, n - 1)
182186

183187
luckynode = pop!(unassigned)
184188
push!(assigned, luckynode)
185189

186-
while length(unassigned) > 0
190+
for iter in 1:(n - 1)
187191
nearestnode, conn = findnearestbetweennodes(conns, distmat, assigned, unassigned)
188192
push!(assigned, nearestnode)
189-
push!(connresult, conn)
193+
connresult[iter] = conn
190194
totaldist += conn.value
191195
unassigned = filter(x -> x != nearestnode, unassigned)
192196
end

test/testmst.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
@test result isa MstResult
8989
@test result.distance == 30.0
9090
@test !hasloop(result.connections)
91+
@test length(result.connections) == length(nodes(conns)) - 1
9192
end
9293

9394
@testset "6 nodes with loops" begin
@@ -113,6 +114,7 @@
113114
end
114115

115116
@test !hasloop(result.connections)
117+
@test length(result.connections) == length(allnodes) - 1
116118
end
117119

118120
@testset "7 nodes with loops" begin
@@ -149,6 +151,7 @@
149151
end
150152

151153
@test !hasloop(result.connections)
154+
@test length(result.connections) == length(allnodes) - 1
152155
end
153156

154157
@testset "big network" begin
@@ -168,5 +171,6 @@
168171
end
169172

170173
@test !hasloop(result.connections)
174+
@test length(result.connections) == length(allnodes) - 1
171175
end
172176
end

0 commit comments

Comments
 (0)