From 54dcabc7ede458942ff374d56066f6dc81dee99e Mon Sep 17 00:00:00 2001 From: Antoine Date: Tue, 24 Nov 2020 01:54:30 +0100 Subject: [PATCH] Add function for retrieve start node and neighboor of given node --- cmd/resolve.go | 9 +++++++++ graph.json | 28 ++++++++++++++++++++++++++++ internal/graph.go | 30 ++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 graph.json diff --git a/cmd/resolve.go b/cmd/resolve.go index 203ac25..44dbd1a 100644 --- a/cmd/resolve.go +++ b/cmd/resolve.go @@ -37,4 +37,13 @@ func main() { for _, p := range graph.Nodes { fmt.Printf("%+v\n", p) } + + start, err := graph.GetStartingNode() + fmt.Printf("%#v\n", start) + + fmt.Printf("neighbourNode of %+v : \n", start) + neig := graph.GetNeighbour(start) + for _, n := range neig { + fmt.Printf("%+v\n", n) + } } diff --git a/graph.json b/graph.json new file mode 100644 index 0000000..1c1cb53 --- /dev/null +++ b/graph.json @@ -0,0 +1,28 @@ +{ + "graph": [ + { + "links": [ + { + "from": "A", + "oriented": false, + "to": "B", + "value": 10 + } + ], + "name": "graph1", + "nodes": [ + { + "name": "A", + "start": true + }, + { + "name": "B", + "value": 0 + }, + { + "name": "A" + } + ] + } + ] +} diff --git a/internal/graph.go b/internal/graph.go index 82ea060..3eabe43 100644 --- a/internal/graph.go +++ b/internal/graph.go @@ -10,3 +10,33 @@ type Graph struct { Links []*Link `hcl:"links,block"` } +func (g *Graph) GetStartingNode() (Node, error) { + for i := 0; i < len(g.Nodes); i++ { + n := (*g.Nodes[i]) + if n.IsStart == true { + return n, nil + } + } + return Node{}, errors.New("No start node found") +} + +func (g *Graph) GetNeighbour(n Node) []Node { + var neighbourNodeName []string + for i := 0; i < len(g.Links); i++ { + if g.Links[i].From == n.Name { + neighbourNodeName = append(neighbourNodeName, g.Links[i].To) + } + } + + // create temporary map of node by here name for direct future access + var nodeByName = make(map[string]Node) + for i := 0; i < len(g.Nodes); i++ { + nodeByName[g.Nodes[i].Name] = (*g.Nodes[i]) + } + + var neighbourNode = make([]Node, len(neighbourNodeName)) + for i := 0; i < len(neighbourNodeName); i++ { + neighbourNode[i] = nodeByName[neighbourNodeName[i]] + } + return neighbourNode +}