Skip to content

Commit c5844a1

Browse files
authored
Faster all_neighbors for SimpleDiGraphs (#82)
1 parent 738c5b4 commit c5844a1

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

src/SimpleGraphs/SimpleGraphs.jl

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@ import Base:
1111
import Graphs:
1212
_NI, AbstractGraph, AbstractEdge, AbstractEdgeIter,
1313
src, dst, edgetype, nv, ne, vertices, edges, is_directed,
14-
has_vertex, has_edge, inneighbors, outneighbors, deepcopy_adjlist,
15-
indegree, outdegree, degree, has_self_loops, num_self_loops, insorted
14+
has_vertex, has_edge, inneighbors, outneighbors, all_neighbors,
15+
deepcopy_adjlist, indegree, outdegree, degree, has_self_loops,
16+
num_self_loops, insorted
1617

1718
using Random: GLOBAL_RNG, AbstractRNG
1819

src/SimpleGraphs/simpledigraph.jl

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,3 +566,37 @@ function rem_vertices!(g::SimpleDiGraph{T},
566566

567567
return reverse_vmap
568568
end
569+
570+
function all_neighbors(g::SimpleDiGraph{T}, u::Integer) where T
571+
i, j = 1, 1
572+
in_nbrs, out_nbrs = inneighbors(g, u), outneighbors(g, u)
573+
in_len, out_len = length(in_nbrs), length(out_nbrs)
574+
union_nbrs = Vector{T}(undef, in_len + out_len)
575+
indx = 1
576+
@inbounds while i <= in_len && j <= out_len
577+
if in_nbrs[i] < out_nbrs[j]
578+
union_nbrs[indx] = in_nbrs[i]
579+
i += 1
580+
elseif in_nbrs[i] > out_nbrs[j]
581+
union_nbrs[indx] = out_nbrs[j]
582+
j += 1
583+
else
584+
union_nbrs[indx] = out_nbrs[j]
585+
i += 1
586+
j += 1
587+
end
588+
indx += 1
589+
end
590+
@inbounds while i <= in_len
591+
union_nbrs[indx] = in_nbrs[i]
592+
i += 1
593+
indx += 1
594+
end
595+
@inbounds while j <= out_len
596+
union_nbrs[indx] = out_nbrs[j]
597+
j += 1
598+
indx += 1
599+
end
600+
resize!(union_nbrs, indx-1)
601+
return union_nbrs
602+
end

test/simplegraphs/simplegraphs.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ import Random
129129

130130
@test @inferred(inneighbors(g, 2)) == [1]
131131
@test @inferred(outneighbors(g, 2)) == @inferred(neighbors(g, 2)) == [3]
132+
@test @inferred Set(all_neighbors(g, 2)) == Set(union(inneighbors(g, 2), outneighbors(g, 2)))
132133
@test @inferred(add_vertex!(gc)) # out of order, but we want it for issubset
133134
@test @inferred(g gc)
134135
@test @inferred(has_vertex(gc, 5))

0 commit comments

Comments
 (0)