Skip to content

Commit 75d96a1

Browse files
committed
new SimpleGraph constructor from tuples
1 parent a10ca67 commit 75d96a1

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/SimpleGraphs/simplegraph.jl

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,33 @@ mutable struct SimpleGraph{T<:Integer} <: AbstractSimpleGraph{T}
1515
end
1616
end
1717

18-
function SimpleGraph(ne, fadjlist::Vector{Vector{T}}) where {T}
18+
function SimpleGraph(ne::Integer, fadjlist::Vector{Vector{T}}) where {T}
1919
return SimpleGraph{T}(ne, fadjlist)
2020
end
2121

22+
# initialize a graph by a vector of tuples
23+
"""
24+
SimpleGraph{T}(n, tuples_as_edges)
25+
26+
Construct a `SimpleGraph{T}` with `n` vertices, with the edges specified as a vector of tuples.
27+
The element type `T` is the type of `n`.
28+
29+
## Examples
30+
```jldoctest
31+
julia> using Graphs
32+
33+
julia> SimpleGraph(UInt8(10), [(1,2), (2, 3)])
34+
{10, 2} undirected simple UInt8 graph
35+
```
36+
"""
37+
function SimpleGraph(n::Integer, tuples_as_edges::AbstractVector{Tuple{T,T}}) where {T<:Integer}
38+
g = SimpleGraph{typeof(n)}(n)
39+
for (i, j) in tuples_as_edges
40+
add_edge!(g, i, j)
41+
end
42+
return g
43+
end
44+
2245
eltype(x::SimpleGraph{T}) where {T} = T
2346

2447
# Graph{UInt8}(6), Graph{Int16}(7), Graph{UInt8}()
@@ -299,7 +322,7 @@ function _SimpleGraphFromIterator(iter)::SimpleGraph
299322
g = SimpleGraph{T}()
300323
fadjlist = Vector{Vector{T}}()
301324

302-
while next != nothing
325+
while next !== nothing
303326
(e, state) = next
304327

305328
if !(e isa E)

test/simplegraphs/simplegraphs.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,4 +498,11 @@ using Random: Random
498498
end
499499
# codecov for has_edge(::AbstractSimpleGraph, x, y)
500500
@test @inferred has_edge(DummySimpleGraph(), 1, 2)
501+
502+
@testset "Constructors from tuples" begin
503+
g = SimpleGraph(Int32(4), [(1, 2), (2, 3)])
504+
@test g isa SimpleGraph{Int32}
505+
@test nv(g) == 4
506+
@test ne(g) == 2
507+
end
501508
end

0 commit comments

Comments
 (0)