summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java
blob: 513044e4622703473027e817dd2109c7f9236abc (plain)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package bjc.utils.graph;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.IntStream;

import bjc.utils.data.GenHolder;

/**
 * An adjacency map representing a graph
 * 
 * @author ben
 *
 * @param <T>
 *            The type of the nodes in the graph
 */
public class AdjacencyMap<T> {
	/**
	 * Create an adjacency map from a stream of text
	 * 
	 * @param stream
	 *            The stream of text to read in
	 * @return An adjacency map defined by the text
	 */
	public static AdjacencyMap<Integer> fromStream(InputStream stream) {
		Scanner inputSource = new Scanner(stream);
		inputSource.useDelimiter("\n");

		// First, read in number of vertices
		int numVertices = Integer.parseInt(inputSource.next());

		Set<Integer> vertices = new HashSet<>();
		IntStream.range(0, numVertices)
				.forEach(element -> vertices.add(element));

		// Create the adjacency map
		AdjacencyMap<Integer> adjacencyMap = new AdjacencyMap<>(vertices);

		GenHolder<Integer> row = new GenHolder<>(0);

		inputSource.forEachRemaining((strang) -> {
			String[] parts = strang.split(" ");
			int column = 0;

			for (String part : parts) {
				adjacencyMap.setWeight(row.unwrap(number -> number),
						column, Integer.parseInt(part));

				column++;
			}

			row.transform((number) -> number + 1);
		});

		inputSource.close();

		return adjacencyMap;
	}

	/**
	 * The backing storage of the map
	 */
	private Map<T, Map<T, Integer>> adjacencyMap = new HashMap<>();

	/**
	 * Create a new map from a set of vertices
	 * 
	 * @param vertices
	 *            The set of vertices to create a map from
	 */
	public AdjacencyMap(Set<T> vertices) {
		vertices.forEach(vertex -> {
			Map<T, Integer> vertexRow = new HashMap<>();

			vertices.forEach(
					targetVertex -> vertexRow.put(targetVertex, 0));

			adjacencyMap.put(vertex, vertexRow);
		});
	}

	/**
	 * Check if the graph is directed
	 * 
	 * @return Whether or not the graph is directed
	 */
	public boolean isDirected() {
		GenHolder<Boolean> result = new GenHolder<>(true);

		adjacencyMap.entrySet().forEach(mapEntry -> {
			Set<Entry<T, Integer>> entryVertices =
					mapEntry.getValue().entrySet();
			entryVertices.forEach(targetVertex -> {
				int leftValue = targetVertex.getValue();
				int rightValue = adjacencyMap.get(targetVertex.getKey())
						.get(mapEntry.getKey());

				if (leftValue != rightValue) {
					result.transform((bool) -> false);
				}
			});
		});

		return result.unwrap(bool -> bool);
	}

	/**
	 * Set the weight of an edge
	 * 
	 * @param sourceVertex
	 *            The source node of the edge
	 * @param targetVertex
	 *            The target node of the edge
	 * @param edgeWeight
	 *            The weight of the edge
	 */
	public void setWeight(T sourceVertex, T targetVertex, int edgeWeight) {
		adjacencyMap.get(sourceVertex).put(targetVertex, edgeWeight);
	}

	/**
	 * Convert this to a different graph representation
	 * 
	 * @return The new representation of this graph
	 */
	public Graph<T> toGraph() {
		Graph<T> returnedGraph = new Graph<>();

		adjacencyMap.entrySet().forEach(sourceVertex -> sourceVertex
				.getValue().entrySet()
				.forEach(targetVertex -> returnedGraph.addEdge(
						sourceVertex.getKey(), targetVertex.getKey(),
						targetVertex.getValue())));

		return returnedGraph;
	}

	/**
	 * Convert an adjacency map back into a stream
	 * 
	 * @param outputSource
	 *            The stream to convert to
	 */
	public void toStream(OutputStream outputSource) {
		PrintStream outputPrinter = new PrintStream(outputSource);

		adjacencyMap.entrySet().forEach(sourceVertex -> {
			sourceVertex.getValue().entrySet()
					.forEach(targetVertex -> outputPrinter.printf("%d ",
							targetVertex.getValue()));
			outputPrinter.println();
		});

		outputPrinter.close();
	}
}