diff --git a/src/simpleweightedgraph.jl b/src/simpleweightedgraph.jl index 8750b67..f2bbb21 100644 --- a/src/simpleweightedgraph.jl +++ b/src/simpleweightedgraph.jl @@ -18,7 +18,15 @@ mutable struct SimpleWeightedGraph{T<:Integer, U<:Real} <: AbstractSimpleWeighte end -ne(g::SimpleWeightedGraph) = nnz(g.weights) ÷ 2 +ne(g::SimpleWeightedGraph) = (nnz(g.weights) + nselfloop(g)) ÷ 2 + +function nselfloop(g::SimpleWeightedGraph) + n = 0 + for i in axes(g.weights, 1) + n += g.weights[i, i] != 0 + end + return n +end SimpleWeightedGraph{T}(adjmx::SparseMatrixCSC{U, T}) where {T <: Integer, U <: Real} = SimpleWeightedGraph{T, U}(adjmx) diff --git a/test/simpleweightedgraph.jl b/test/simpleweightedgraph.jl index f526c91..0850a0c 100644 --- a/test/simpleweightedgraph.jl +++ b/test/simpleweightedgraph.jl @@ -2,19 +2,21 @@ using SimpleWeightedGraphs @testset "SimpleWeightedGraphs" begin @info("Ignore warnings relating to adding and removing vertices and edges") - adjmx1 = [0 1 0; 1 0 1; 0 1 0] # SimpleWeightedGraph - adjmx2 = [0 1 0; 1 0 1; 1 1 0] # SimpleWeightedDiGraph + adjmx1 = [0 1 0; 1 1 1; 0 1 0] # SimpleWeightedGraph + adjmx2 = [0 1 0; 1 1 1; 1 1 0] # SimpleWeightedDiGraph # specific concrete generators - no need for loop @test @inferred(eltype(SimpleWeightedGraph())) == Int @test @inferred(eltype(SimpleWeightedGraph(adjmx1))) == Int @test_throws ErrorException SimpleWeightedGraph(adjmx2) @test @inferred(ne(SimpleWeightedGraph(path_digraph(5)))) == 4 + @test @inferred(ne(SimpleWeightedGraph(adjmx1))) == 3 @test @inferred(!is_directed(SimpleWeightedGraph)) @test @inferred(eltype(SimpleWeightedDiGraph())) == Int @test @inferred(eltype(SimpleWeightedDiGraph(adjmx2))) == Int @test @inferred(ne(SimpleWeightedDiGraph(path_graph(5)))) == 8 + @test @inferred(ne(SimpleWeightedDiGraph(adjmx2))) == 6 @test @inferred(is_directed(SimpleWeightedDiGraph))