package BackendManagers; import BackendManagers.Interfaces.WorldBuildingUtilInterface; import CommonUtils.MST; import CommonUtils.UsefulContainers.iPair; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.List; /** * Contains helpful functions for dealing with our world building. Will not be integrated with * production classes, as it is a tool for helping us with content creation. * * 251 students: you may use any of the data structures you have previously created, but may not use * any Java util library except List/ArrayList and java.util.stream.* . */ public class WorldBuildingUtil implements WorldBuildingUtilInterface { private static double euclideanDistance(iPair p, iPair q) { return Math.sqrt(Math.pow(p.a - q.a, 2) + Math.pow(p.b - q.b, 2)); } /** * Selects roads per the specifications (minimum cost to connect all cities). * * @param filename file to read input from * @return list of roads, per the specifications */ @Override public List getMinimumConnectingRoads(String filename) { try { BufferedReader bf = new BufferedReader(new FileReader(filename)); int C = Integer.parseInt(bf.readLine()); double[][] weights = new double[C][C]; iPair[] coords = new iPair[C]; // Read in city coordinates for (int i = 0; i < C; i++) { String[] in = bf.readLine().split(" "); int a = Integer.parseInt(in[0]); int b = Integer.parseInt(in[1]); iPair coord = new iPair(a, b); coords[i] = coord; // Update distances to all previous cities for (int j = 0; j < i; j++) { double dist = euclideanDistance(coords[i], coords[j]); weights[i][j] = dist; weights[j][i] = dist; } } return MST.denseMST(weights) .stream() .map(p -> new CityEdge(coords[p.a], coords[p.b])) .toList(); } catch (IOException e) { //This should never happen... uh oh o.o System.err.println("ATTENTION TAs: Couldn't find test file: \"" + filename + "\":: " + e.getMessage()); System.exit(1); } return null; } }