From f6f60fe3ac3d6d460249493421466213a4930f49 Mon Sep 17 00:00:00 2001 From: Felix Hillingshaeuser Date: Thu, 4 Jul 2024 15:43:57 +0200 Subject: [PATCH] add function to get a list of all vertices in the graph --- graph.go | 11 +++++++++++ graph_test.go | 19 ++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/graph.go b/graph.go index 29a033d..a7870b6 100644 --- a/graph.go +++ b/graph.go @@ -225,3 +225,14 @@ func (g Graph) validate() error { } return nil } + +// GetVertices returns all indexes of all vertices +func (g Graph) GetVertices() []int { + var vertices []int + for idx, vertex := range g.vertexArcs { + if vertex != nil { + vertices = append(vertices, idx) + } + } + return vertices +} diff --git a/graph_test.go b/graph_test.go index 879916e..0990804 100644 --- a/graph_test.go +++ b/graph_test.go @@ -1,6 +1,9 @@ package dijkstra -import "testing" +import ( + "reflect" + "testing" +) func TestGetVertex(t *testing.T) { g := NewGraph() @@ -74,3 +77,17 @@ func TestValidateCorrect(t *testing.T) { } } } + +func TestGetVertices(t *testing.T) { + g := NewGraph() + g.AddEmptyVertex(0) + expectedResult := []int{0} + if !reflect.DeepEqual(g.GetVertices(), expectedResult) { + t.Errorf("Graph should have vertices [0] but has %v", g.GetVertices()) + } + g.AddEmptyVertex(4) + expectedResult = []int{0, 4} + if !reflect.DeepEqual(g.GetVertices(), expectedResult) { + t.Errorf("Graph should have vertices [0,4] but has %v", g.GetVertices()) + } +}