Add function for retrieve start node and neighboor of given node
This commit is contained in:
parent
04b67c5f3a
commit
54dcabc7ed
@ -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)
|
||||
}
|
||||
}
|
||||
|
28
graph.json
Normal file
28
graph.json
Normal file
@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
@ -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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user