69 lines
1.8 KiB
Go
69 lines
1.8 KiB
Go
|
package graph
|
||
|
|
||
|
//Node a graph node which can contain connections to other nodes
|
||
|
type Node struct {
|
||
|
Value string
|
||
|
connections []*Node
|
||
|
messages []string
|
||
|
}
|
||
|
|
||
|
//GetConnections returns all connections
|
||
|
func (n *Node) GetConnections() []*Node {
|
||
|
return n.connections
|
||
|
}
|
||
|
|
||
|
//GetMessages returns all messages in this Node
|
||
|
func (n *Node) GetMessages() []string {
|
||
|
return n.messages
|
||
|
}
|
||
|
|
||
|
//Connect connects two nodes
|
||
|
func (n *Node) Connect(otherNode *Node) {
|
||
|
//nref := &otherNode
|
||
|
n.connections = append(n.connections, otherNode)
|
||
|
otherNode.connections = append(otherNode.connections, n)
|
||
|
}
|
||
|
|
||
|
//Disconnect disconnects to nodes
|
||
|
func (n *Node) Disconnect(otherNode *Node) int {
|
||
|
i := n.GetIndexOf(otherNode)
|
||
|
j := otherNode.GetIndexOf(n)
|
||
|
if i != -1 && j != -1 {
|
||
|
//remove othernode from n.connections, and remove n from otherNode.connections
|
||
|
n.connections = append(n.connections[:i], n.connections[i+1:]...)
|
||
|
otherNode.connections = append(otherNode.connections[:j], otherNode.connections[j+1:]...)
|
||
|
return 1
|
||
|
}
|
||
|
return -1
|
||
|
}
|
||
|
|
||
|
//IsConnectedTo checks if this node is connected to the given node
|
||
|
func (n *Node) IsConnectedTo(otherNode *Node) bool {
|
||
|
if n.GetIndexOf(otherNode) != -1 {
|
||
|
return true
|
||
|
}
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
//GetIndexOf gets the index of the specified node
|
||
|
func (n *Node) GetIndexOf(otherNode *Node) int {
|
||
|
for i := range n.connections {
|
||
|
//fmt.Printf("%p and %p \n", n.connections[i], otherNode)
|
||
|
|
||
|
if n.connections[i] == otherNode { //addresses are compared
|
||
|
return i
|
||
|
}
|
||
|
}
|
||
|
return -1
|
||
|
}
|
||
|
|
||
|
//NrOfConnectedNodes number of nodes connected to this node
|
||
|
func (n *Node) NrOfConnectedNodes() int {
|
||
|
return len(n.connections)
|
||
|
}
|
||
|
|
||
|
//InsertMessage inserts a string message in the messages field of this node
|
||
|
func (n *Node) InsertMessage(message string) {
|
||
|
n.messages = append(n.messages, message) //append returns a new slice, so we have to replace it
|
||
|
}
|