Created
May 15, 2015 20:06
-
-
Save fge/ab6845a97d480eebba94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.HashMap; | |
import java.util.HashSet; | |
import java.util.Iterator; | |
import java.util.Map; | |
import java.util.Objects; | |
import java.util.Set; | |
import java.util.regex.Pattern; | |
public final class Foo | |
{ | |
private static final Pattern PATTERN = Pattern.compile("\\s*:\\s*"); | |
private static final class AdjMatrix | |
implements Iterable<String> | |
{ | |
private final Set<String> edges = new HashSet<>(); | |
private final Map<Vertex, Integer> vertices = new HashMap<>(); | |
// PRIVATE!! | |
private void addEdges(final String edge1, final String edge2) | |
{ | |
edges.add(edge1); | |
edges.add(edge2); | |
} | |
private void addVertex(final Vertex vertex, final int weight) | |
{ | |
addEdges(vertex.from, vertex.to); | |
if (vertices.put(vertex, weight) != null) | |
throw new IllegalStateException(); | |
} | |
@Override | |
public Iterator<String> iterator() | |
{ | |
return edges.iterator(); | |
} | |
} | |
public static void main(final String... args) | |
throws IOException | |
{ | |
final AdjMatrix matrix = new AdjMatrix(); | |
final Path path = Paths.get(System.getProperty("user.home"), "FOO.txt"); | |
try ( | |
final BufferedReader reader = Files.newBufferedReader(path); | |
) { | |
String line; | |
String[] parts; | |
String edge1; | |
String edge2; | |
int weight; | |
Vertex v; | |
while ((line = reader.readLine()) != null) { | |
parts = PATTERN.split(line); | |
edge1 = parts[0]; | |
edge2 = parts[1]; | |
weight = Integer.parseInt(parts[2]); | |
v = new Vertex(edge1, edge2); | |
matrix.addVertex(v, weight); | |
v = new Vertex(edge2, edge1); | |
matrix.addVertex(v, weight); | |
} | |
} | |
} | |
private static final class Vertex | |
{ | |
private final String from; | |
private final String to; | |
Vertex(final String from, final String to) | |
{ | |
this.from = from; | |
this.to = to; | |
} | |
@Override | |
public int hashCode() | |
{ | |
return Objects.hash(from, to); | |
} | |
@Override | |
public boolean equals(final Object obj) | |
{ | |
if (obj == null) | |
return false; | |
if (getClass() != obj.getClass()) | |
return false; | |
final Vertex other = (Vertex) obj; | |
return from.equals(other.from) | |
&& to.equals(other.to); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment