package reader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import dijkstra.DijkstraShortestPathsAlgorithm.Vertice;
public class DijkstraGraphReader {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
Map<Integer, Vertice> result = readGraphFromFile("dijkstra/dijkstraData.txt");
System.out.println(String.format("Verticies count is %d ", result.size()));
for (Entry<Integer, Vertice> vertice: result.entrySet()) {
System.out.print(vertice.toString());
for (Entry<Integer, Integer> entry : vertice.getValue().getAdjacentVerticies().entrySet()) {
System.out.print(String.format(" %d,%d",
entry.getKey(), entry.getValue()));
}
System.out.println();
}
}
public static Map<Integer, Vertice> readGraphFromFile(String filePath)
throws FileNotFoundException {
Map<Integer, Vertice> result = new HashMap<>();
Scanner scan = new Scanner(new File(filePath));
while(scan.hasNextLine()) {
processLine(scan.nextLine(), result);
}
scan.close();
return result;
}
private static void processLine(String line, Map<Integer, Vertice> result) {
Vertice lineVertice = getVerticeFromLine(line);
result.put(lineVertice.getName(), lineVertice);
}
private static Vertice getVerticeFromLine(String line) {
String[] graphWithAdjacents = line.split(" ");
Vertice vertice = new Vertice(
Integer.valueOf(graphWithAdjacents[0]),
getAdjacentVericies(graphWithAdjacents));
return vertice;
}
private static Map<Integer, Integer> getAdjacentVericies(String[] graphWithAdjacents){
Map<Integer, Integer> result = new LinkedHashMap<>();
for(int i=1; i<graphWithAdjacents.length; i++) {
String pair = graphWithAdjacents[i];
String[] verticeWithDistancePair = pair.split(",");
result.put(Integer.valueOf(verticeWithDistancePair[0]),
Integer.valueOf(verticeWithDistancePair[1]));
}
return result;
}
}