/**
* Map of towns, indexed by their names
*/
private Map<String, Town> busNetwork = new HashMap<String, Town>();
private List<String> townOrder = new ArrayList<>();
Map<String, Point2D.Double> coords = new HashMap<>();
/**
* CORE
* Loads a network of towns from a file.
* Constructs a Map of Town objects in the busNetwork field
* Each town has a name and a set of neighbouring towns
* First line of file contains the names of all the towns.
* Remaining lines have pairs of names of towns that are connected.
*/
public void loadNetwork(String filename) {
try {
busNetwork.clear();
townOrder.clear();
UI.clearText();
List<String> lines = Files.readAllLines(Path.of(filename));
String firstLine = lines.remove(0);
int start = 0;
try {
start = Integer.parseInt(firstLine);
UI.println("number: " + start);
for (int i = 0; i < start; i++) {
String name = lines.get(i).split(" ")[0].trim();
double lat = Double.parseDouble(lines.get(i).split(" ")[1].trim());
double lon = Double.parseDouble(lines.get(i).split(" ")[2].trim());
busNetwork.put(name, new Town(name));
coords.put(name, new Point2D.Double(lat,lon));
townOrder.add(name);
}
} catch (NumberFormatException e) { //parsing fails; is string
UI.println("Loaded file with coordinates");
}
List<String> cutLines = lines.subList(start,lines.size());
if (start == 0) {
String[] townNames = firstLine.split(" ");
for (String name : townNames) {
busNetwork.put(name, new Town(name));
townOrder.add(name);
}
}
// Process the remaining lines to add connections between towns
for (String line : cutLines) {
String[] towns = line.split(" ");
Town town1 = busNetwork.get(towns[0]);
Town town2 = busNetwork.get(towns[1]);
if (town1 != null && town2 != null) {
town1.addNeighbour(town2);
town2.addNeighbour(town1);
}
}
UI.println("Loaded " + busNetwork.size() + " towns:");
} catch (IOException e) {
throw new RuntimeException("Loading data.txt failed" + e);
}
}
/**
* CORE
* Print all the towns and their neighbours:
* Each line starts with the name of the town, followed by
* the names of all its immediate neighbours,
*/
public void printNetwork() {
UI.println("The current network: \n====================");
for (String townName : townOrder) {
Town town = busNetwork.get(townName);
StringBuilder sb = new StringBuilder(town.getName() + "-> ");
List<String> neighborNames = new ArrayList<>();
for (Town neighbour : town.getNeighbours()) {
neighborNames.add(neighbour.getName());
}
Collections.sort(neighborNames);
sb.append(String.join(" ", neighborNames));
UI.println(sb.toString());
}
}
/**
* COMPLETION
* Return a set of all the nodes that are connected to the given node.
* Traver se the network from this node in the standard way, using a
* visited set, and then return the visited set
*/
public Set<Town> findAllConnected(Town town) {
/*# YOUR CODE HERE */
Set<Town> visited = new HashSet<>();
findRecur(visited, town);
return visited;
}
public void findRecur(Set<Town> seen, Town town) {
if (seen.contains(town)) return;
seen.add(town);
town.getNeighbours().forEach(t -> findRecur(seen, t));
}
//public Set
/**
* COMPLETION
* Print all the towns that are reachable through the network from
* the town with the given name.
* Note, do not include the town itself in the list.
*/
public void printReachable(String name) {
Town town = busNetwork.get(name);
if (town == null) {
UI.println(name + " is not a recognised town");
} else {
UI.println("\nFrom " + town.getName() + " you can get to:");
/*# YOUR CODE HERE */
Set<Town> reachable = findAllConnected(town);
reachable.remove(town);
reachable.forEach(t -> UI.print(t.getName() + " "));
}
}
/**
* COMPLETION
* Print all the connected sets of towns in the busNetwork
* Each line of the output should be the names of the towns in a connected set
* Works through busNetwork, using findAllConnected on each town that hasn't
* yet been printed out.
*/
public void printConnectedGroups() {
UI.println("Groups of Connected Towns: \n================");
int groupNum = 1;
/*# YOUR CODE HERE */
Set<Town> group = new HashSet<>();
Set<Town> visited = new HashSet<>(group);
for (Town town : busNetwork.values()) {
if (!visited.contains(town)) {
group.addAll(findAllConnected(town));
UI.print("\n Group " + groupNum + ": ");
group.forEach(t -> UI.print(t.getName() + " "));
groupNum++;
visited.addAll(group);
group.clear();
}
}
}
public void displayGraph(){
UI.clearGraphics();
}
/**
* Set up the GUI (buttons and mouse)
*/
public void setupGUI() {
UI.addButton("Load", () -> {
loadNetwork(UIFileChooser.open());
});
UI.addButton("Print Network", this::printNetwork);
UI.addTextField("Reachable from", this::printReachable);
UI.addButton("All Connected Groups", this::printConnectedGroups);
UI.addButton("Display graph", this::displayGraph);
UI.addButton("Clear", UI::clearText);
UI.addButton("Quit", UI::quit);
UI.setWindowSize(1100, 500);
UI.setDivider(1.0);
//loadNetwork("data-small.txt");
}
// Main
public static void main(String[] arguments) {
BusNetworks bnw = new BusNetworks();
bnw.setupGUI();
}
how the coordinates are given:
Ashburton -43.89834 171.73011
Auckland -36.86667 174.76667
Blenheim -41.51603 173.9528
Christchurch -43.53333 172.63333
Dunedin -45.87416 170.50361
FoxGlacier -43.46460 170.01782
FranzJosef -43.46386 170.18825
Gisborne -38.65333 178.00417
Gore -46.10282 168.94357
Greymouth -42.46667 171.2
Hamilton -37.78333 175.28333
Hastings -39.6381 176.84918
Hokitika -42.71737 170.96654
Invercargill -46.4 168.35
Kaikoura -42.40082 173.68139
Kaitaia -35.11733 173.26756
Kerikeri -35.22676 173.94739
Levin -40.63333 175.275
Matamata -37.8106 175.76237
Napier -39.48333 176.91667
Nelson -41.27078 173.28404
NewPlymouth -39.06667 174.08333
Oamaru -45.09746 170.96911
Paihia -35.28067 174.09103
PalmerstonNorth -40.35636 175.61113
Picton -41.29059 174.001
Punakaiki -42.10841 171.33631
Queenstown -45.03023 168.66271
Rotorua -38.13874 176.24516
Taupo -38.68333 176.08333
Tauranga -37.68611 176.16667
TeAnau -45.41667 167.71667
Tekapo -44.00467 170.47712
Thames -37.13832 175.54011
Timaru -44.4 171.25
Wanaka -44.69574 169.11156
Wanganui -39.93333 175.05
Wellington -41.28664 174.77557
Westport -41.75262 171.6037
Whakatane -37.95855 176.98545
Whangarei -35.73167 174.32391
Whitianga -36.82183 175.70044
for (String townName : townOrder) {
// Calculate screen coordinates
int x = (int)(padding + extraX + (lon - minLon) * scale);
int y = (int)(windowHeight - padding - extraY - (lat - minLat) * scale); // Invert Y-axis
// Draw the town
UI.setColor(Color.BLUE);
UI.fillOval(x - 3, y - 3, 6, 6);
// Label the town
UI.setColor(Color.BLACK);
UI.drawString(townName, x + 5, y - 5);
}
import ecs100.*;
import java.awt.*;
import java.awt.geom.Point2D;
import java.io.*;
import java.util.*;
import java.nio.file.*;
import java.util.List;
public class BusNetworks {
// ... [Existing fields and methods]
public void displayGraph(){
UI.clearGraphics();
// Define window size based on UI settings
int windowWidth = 1000; // Adjust if necessary
int windowHeight = 500; // Adjust if necessary
// Define padding to avoid drawing at the very edge
int padding = 50;
// Initialize min and max values for latitude and longitude
double minLat = Double.MAX_VALUE;
double maxLat = -Double.MAX_VALUE;
double minLon = Double.MAX_VALUE;
double maxLon = -Double.MAX_VALUE;
// Determine the minimum and maximum latitude and longitude
for (Point2D.Double point : coords.values()) {
double lat = point.x;
double lon = point.y;
if (lat < minLat) minLat = lat;
if (lat > maxLat) maxLat = lat;
if (lon < minLon) minLon = lon;
if (lon > maxLon) maxLon = lon;
}
// Calculate the range of latitude and longitude
double latRange = maxLat - minLat;
double lonRange = maxLon - minLon;
// Compute scaling factors for X and Y axes
double scaleX = (windowWidth - 2.0 * padding) / lonRange;
double scaleY = (windowHeight - 2.0 * padding) / latRange;
// Use the smaller scale to maintain aspect ratio
double scale = Math.min(scaleX, scaleY);
// Centering the graph if there's extra space
double extraX = (windowWidth - 2.0 * padding - (lonRange * scale)) / 2.0;
double extraY = (windowHeight - 2.0 * padding - (latRange * scale)) / 2.0;
// Iterate through each town and plot it
for (String townName : townOrder) {
Point2D.Double point = coords.get(townName);
double lat = point.x;
double lon = point.y;
// Calculate screen coordinates
int x = (int)(padding + extraX + (lon - minLon) * scale);
int y = (int)(windowHeight - padding - extraY - (lat - minLat) * scale); // Invert Y-axis
// Draw the town as a filled oval (circle)
UI.setColor(Color.BLUE);
UI.fillOval(x - 3, y - 3, 6, 6); // Adjust size as needed
// Optionally, draw the town name next to the point
UI.setColor(Color.BLACK);
UI.drawString(townName, x + 5, y - 5); // Position label slightly offset
}
// Optional: Draw connections between towns
UI.setColor(Color.GRAY);
for (String townName : townOrder) {
Town town = busNetwork.get(townName);
Point2D.Double fromPoint = coords.get(townName);
double fromLat = fromPoint.x;
double fromLon = fromPoint.y;
int fromX = (int)(padding + extraX + (fromLon - minLon) * scale);
int fromY = (int)(windowHeight - padding - extraY - (fromLat - minLat) * scale);
for (Town neighbor : town.getNeighbours()) {
Point2D.Double toPoint = coords.get(neighbor.getName());
double toLat = toPoint.x;
double toLon = toPoint.y;
int toX = (int)(padding + extraX + (toLon - minLon) * scale);
int toY = (int)(windowHeight - padding - extraY - (toLat - minLat) * scale);
// Draw a line between the two towns
UI.drawLine(fromX, fromY, toX, toY);
}
}
}
// ... [Rest of the class]
// Main method and other methods remain unchanged
}