aboutsummaryrefslogtreecommitdiff
path: root/Practical1/src/nl/camilstaps/cs/graphs/Graph.java
blob: ef8925882eac6f9d0aae0bc78457ae3a7427b803 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package nl.camilstaps.cs.graphs;

import java.util.*;
import java.util.stream.Collectors;

/**
 * A Graph is a list of Nodes.
 *
 * @author Camil Staps
 */
public class Graph {
    protected final List<Node> nodes;

    public Graph() {
        this.nodes = new ArrayList<>();
    }

    /**
     * Create a copy of another Graph, also copying all the Nodes
     * @param g
     */
    public Graph(Graph g) {
        this();
        this.nodes.addAll(g.nodes.stream().map(Node::new).collect(Collectors.toList()));
    }

    /**
     * Add a Node
     * @param node
     */
    public void addNode(Node node) {
        this.nodes.add(node);
    }

    /**
     * Get a Node
     * @param i
     * @return
     */
    public Node getNode(int i) {
        return this.nodes.get(i);
    }

    /**
     * Remove a node
     * @param n
     */
    public void removeNode(Node n) {
        nodes.remove(n);
    }

    /**
     * Remove a list of nodes, and update all references
     * @param ns
     */
    public void removeNodes(Collection<Node> ns) {
        nodes.removeAll(ns);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder("Graph:");
        for (Node n : nodes) {
            sb.append("\n  ").append(n).append(":   ");
            for (Node n2 : n.getNeighbours()) sb.append(" - ").append(n2);
        }
        return sb.toString();
    }
}