summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java
blob: 247ee31f48026b7bdccf86dd60e690c76fb13560 (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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
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.InputMismatchException;
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) {
		if (stream == null) {
			throw new NullPointerException(
					"Input source must not be null");
		}

		// Create the adjacency map
		AdjacencyMap<Integer> adjacencyMap;

		try (Scanner inputSource = new Scanner(stream)) {
			inputSource.useDelimiter("\n");

			int numVertices;

			String possibleVertices = inputSource.next();

			try {
				// First, read in number of vertices
				numVertices = Integer.parseInt(possibleVertices);
			} catch (NumberFormatException nfex) {
				InputMismatchException imex = new InputMismatchException(
						"The first line must contain the number of vertices. "
								+ possibleVertices
								+ " is not a valid number");

				imex.initCause(nfex);

				throw imex;
			}

			if (numVertices <= 0) {
				throw new InputMismatchException(
						"The number of vertices must be greater than 0");
			}

			Set<Integer> vertices = new HashSet<>();

			IntStream.range(0, numVertices)
					.forEach(element -> vertices.add(element));

			adjacencyMap = new AdjacencyMap<>(vertices);

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

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

				if (parts.length != numVertices) {
					throw new InputMismatchException(
							"Must specify a weight for all " + numVertices
									+ " vertices");
				}

				int column = 0;

				for (String part : parts) {
					int columnWeight;

					try {
						columnWeight = Integer.parseInt(part);
					} catch (NumberFormatException nfex) {
						InputMismatchException imex = new InputMismatchException(
								"" + part + " is not a valid weight.");

						imex.initCause(nfex);

						throw imex;
					}

					adjacencyMap.setWeight(row.unwrap(number -> number),
							column, columnWeight);

					column++;
				}

				row.transform((number) -> {
					int newNumber = number + 1;

					return newNumber;
				});
			});
		}

		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) {
		if (vertices == null) {
			throw new NullPointerException("Vertices must not be null");
		}

		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) {
		if (sourceVertex == null) {
			throw new NullPointerException(
					"Source vertex must not be null");
		} else if (targetVertex == null) {
			throw new NullPointerException(
					"Target vertex must not be null");
		}

		if (!adjacencyMap.containsKey(sourceVertex)) {
			throw new IllegalArgumentException("Source vertex "
					+ sourceVertex + " isn't present in map");
		} else if (!adjacencyMap.containsKey(targetVertex)) {
			throw new IllegalArgumentException("Target vertex "
					+ targetVertex + " isn't present in map");
		}

		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 outputSink
	 *            The stream to convert to
	 */
	public void toStream(OutputStream outputSink) {
		if (outputSink == null) {
			throw new NullPointerException(
					"Output source must not be null");
		}

		PrintStream outputPrinter = new PrintStream(outputSink);

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

		outputPrinter.close();
	}
}