Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faster dorogovtsev mendes #371

Merged
merged 6 commits into from
May 1, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 24 additions & 16 deletions src/SimpleGraphs/generators/randgraphs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1494,24 +1494,32 @@ function dorogovtsev_mendes(
n < 3 && throw(DomainError("n=$n must be at least 3"))
rng = rng_from_rng_or_seed(rng, seed)
g = cycle_graph(3)

for iteration in 1:(n - 3)
chosenedge = rand(rng, 1:(2 * ne(g))) # undirected so each edge is listed twice in adjlist
u, v = -1, -1
for i in 1:nv(g)
edgelist = outneighbors(g, i)
if chosenedge > length(edgelist)
chosenedge -= length(edgelist)
else
u = i
v = edgelist[chosenedge]
break
end
end

add_vertex!(g)
bag_of_edges = Vector{SimpleEdge{Int}}(undef, 2 * n - 3) # Caching edges as they are added to avoid costly lookups

bag_of_edges[1] = SimpleEdge(1, 2)
bag_of_edges[2] = SimpleEdge(1, 3)
bag_of_edges[3] = SimpleEdge(2, 3)
index = 3

for _ in 1:(n - 3)
# Choose random edge from bag
edge = bag_of_edges[rand(rng, 1:index)]
u, v = edge.src, edge.dst

# Add new vertex
add_vertex!(g) || throw(
DomainError(
"Failed to add vertex. One possible explanation is that type $(eltype(g)) cannot represent enough vertices",
),
)
# Add new edges
add_edge!(g, nv(g), u)
add_edge!(g, nv(g), v)

# Add new edges to bag
bag_of_edges[index + 1] = SimpleEdge(nv(g), edge.src)
bag_of_edges[index + 2] = SimpleEdge(nv(g), edge.dst)
index += 2
end
return g
end
Expand Down
13 changes: 13 additions & 0 deletions test/simplegraphs/generators/randgraphs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,19 @@
@test δ(g) == 2
g = dorogovtsev_mendes(3; rng=rng)
@test nv(g) == 3 && ne(g) == 3
@test δ(g) == 2 && Δ(g) == 2

# Testing that n=4 graph is one on the possible graphs
g = dorogovtsev_mendes(4; rng=rng)
@test has_edge(g, 1, 2) &&
has_edge(g, 1, 3) &&
has_edge(g, 2, 3) &&
(
has_edge(g, 1, 4) && has_edge(g, 2, 4) ||
has_edge(g, 2, 4) && has_edge(g, 3, 4) ||
has_edge(g, 1, 4) && has_edge(g, 3, 4)
)

# testing domain errors
@test_throws DomainError dorogovtsev_mendes(2, rng=rng)
@test_throws DomainError dorogovtsev_mendes(-1, rng=rng)
Expand Down
Loading