package graph import ( "fmt" ) //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) { n.connections = append(n.connections, otherNode) otherNode.connections = append(otherNode.connections, n) } //SetPointTo sets this Node to point towards the given Node func (n *Node) SetPointTo(otherNode *Node) { n.connections = append(n.connections, otherNode) } //RemovePointerTo removes pointer to a node (a "child") func (n *Node) RemovePointerTo(otherNode *Node) int { fmt.Println(otherNode) i := n.GetIndexOf(otherNode) if i != -1 { n.connections = append(n.connections[:i], n.connections[i+1:]...) return i } return -1 } //Disconnect disconnects two nodes by removing pointers for BOTH 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 (has a pointer) 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 }