Question: I need help fixing this program. Below I have the code for the classes and the errors (part of code runs until it hits a

I need help fixing this program. Below I have the code for the classes and the errors (part of code runs until it hits a certain point):

Error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 51, Size: 29

at java.util.ArrayList.rangeCheck(Unknown Source)

at java.util.ArrayList.get(Unknown Source)

at WeightedGraph.createWeightedGraph(WeightedGraph.java:106)

at WeightedGraph.(WeightedGraph.java:50)

at CityRoadMap.(CityRoadMap.java:27)

at NCCitiesRoads.buildSubMap(NCCitiesRoads.java:359)

at NCCitiesRoads.processCmd(NCCitiesRoads.java:92)

at NCCitiesRoads.main(NCCitiesRoads.java:68)

**************CityRoadMap Class****************

import java.util.*;

public class CityRoadMap extends WeightedGraph {

/** Construct an empty road map */

public CityRoadMap() {

}

/** Construct a CityRoadMap using cities and roads stored in lists */

public CityRoadMap(List vertices, List edges) {

// Let the WeightedGraph superclass build the graph/map

// Call the superclass constructor passing in parameters

// code this line

super(vertices, edges);

}

/**

* Return the neighbors of the City object vertex as an ArrayList of City

* objects

*/

public List getNeighbors(V v) {

// Create the ArrayList to return'

ArrayList arrNeighbors = new ArrayList<>();

// Find the index of City v

int index = this.vertices.indexOf(v);

// Loop through the neighbors adjacency list of Edges

// Then add the adjacent City to the ArrayList to return

// code this for each loop that adds adjacent City to ArrayList

for (int i = 0; i < neighbors.get(index).size(); i++) {

int endVertex = neighbors.get(index).get(i).v;

arrNeighbors.add(vertices.get(endVertex));

}

// Return the ArrayList of Vertices (Cities)

return arrNeighbors;

}

/** Display cities and roads with distances and direction */

public String printRoads() {

// Initialize String to return

String roads = "";

// Loop through the vertices ArrayList, retrieving the City

// vertex and then the corresponding neighbors adjacency list

for (int i = 0; i < vertices.size(); i++) {

// Retrieve the vertex and cast it to a City object

City current = (City) vertices.get(i);

// Call the printCity method of the City object and add to String

roads += current.printCity() + " ";

// Loop through the neighbors adjacency list for the adjacent City

// retrieving each edge

for (int j = i; j < neighbors.get(i).size(); j++) {

// Cast the Edge to a Road and call the Road printRoad method

Road currEdg = (Road) neighbors.get(i).get(j);

// Add the method output to the string to return

roads += currEdg.printRoad() + " ";

}

}

// return the String

return roads;

}

/** Display cities with GPS coordinates and population */

public String printCities() {

// Initialize String to return

String cities = "";

// Loop through the vertices ArrayList, retrieving the City

for (V vertice : vertices) {

// Retrieve the vertex and cast it to a City object

City current = (City) vertice;

// Call the printCity method of the City object to get

cities += current.printCity() + " ";

}

// return the String

return cities;

}

}

*******************WeightedGraph Class*****************

import java.util.*;

@SuppressWarnings("unchecked")

public class WeightedGraph extends AbstractGraph

{

/** Construct an empty graph */

public WeightedGraph()

{

}

/**

* Construct a WeightedGraph from vertex array

* and edges stored in an adjacency matrix

*/

public WeightedGraph(V[] vertices, int[][] edges)

{

createWeightedGraph (java.util.Arrays.asList (vertices), edges);

}

/**

* Construct a WeightedGraph from Integer vertices

* and edges stored in an adjacency matrix

*/

public WeightedGraph (int[][] edges, int numVertices)

{

List vertices = new ArrayList<>();

for (int i = 0; i < numVertices; i++)

{

vertices.add ((V)(new Integer (i)));

}

createWeightedGraph (vertices, edges);

}

/** Construct a WeightedGraph vertices and edges stored in lists */

public WeightedGraph (List vertices, List edges)

{

createWeightedGraph (vertices, edges);

}

/** Construct a WeightedGraph from Integer vertices and edge list */

public WeightedGraph (List edges, int numVertices)

{

List vertices = new ArrayList<>();

for (int i = 0; i < numVertices; i++)

{

vertices.add ((V)(new Integer (i)));

}

createWeightedGraph (vertices, edges);

}

/**

* Create an edge adjacency list for each vertex

* from edges stored in an adjacency matrix

*/

private void createWeightedGraph (List vertices, int[][] edges)

{

this.vertices = vertices;

for (int i = 0; i < vertices.size(); i++)

{

// Create a list for vertices

neighbors.add (new ArrayList());

}

for (int i = 0; i < edges.length; i++)

{

neighbors.get (edges[i][0]).add (new WeightedEdge

(edges[i][0], edges[i][1], edges[i][2]));

}

}

/**

* Create an edge adjacency list for each vertex in

* the vertex list from edges stored in a list

*/

private void createWeightedGraph (List vertices, List edges)

{

this.vertices = vertices;

for (int i = 0; i < vertices.size(); i++)

{

// Create a list for vertices

neighbors.add (new ArrayList());

}

for (WeightedEdge edge: edges)

{

// Add an edge into the list

neighbors.get (edge.u).add (edge);

}

}

/** Return the weight on the edge (u, v) */

public double getWeight (int u, int v) throws Exception

{

for (Edge edge : neighbors.get (u))

{

if (edge.v == v)

{

return( (WeightedEdge) edge).weight;

}

}

throw new Exception ("Edge does not exit");

}

/** Display edges with weights */

public void printWeightedEdges()

{

for (int i = 0; i < getSize(); i++)

{

System.out.print (getVertex(i) + " (" + i + "): ");

for (Edge edge : neighbors.get (i))

{

double wt = ((WeightedEdge)edge).weight;

System.out.print ("(" + edge.u + ", " + edge.v + ", "

+ Math.round(wt*100)/100.0 + ") ");

}

System.out.println();

}

}

/** Add the edge to the weighted graph */

public boolean addEdge (int u, int v, double weight)

{

return addEdge (new WeightedEdge (u, v, weight));

}

/** Get a minimum spanning tree rooted at vertex 0 */

public MST getMinimumSpanningTree()

{

return getMinimumSpanningTree (0);

}

/** Get a minimum spanning tree rooted at a specified vertex */

public MST getMinimumSpanningTree (int startingVertex)

{

// The array element cost[v] stores the cost by adding v to the tree

double[] cost = new double[getSize()];

for (int i = 0; i < cost.length; i++)

{

cost[i] = Double.POSITIVE_INFINITY; // Initial cost

}

cost[startingVertex] = 0; // Cost of source is 0

// Parent of a vertex

int[] parent = new int[getSize()];

// StartingVertex is the root

parent[startingVertex] = -1;

// Total weight of the tree thus far

double totalWeight = 0;

// T stores the vertices in MST found so far

List T = new ArrayList<>();

// Expand T until it has all the vertices

while (T.size() < getSize())

{

// Vertex to be determined

int u = -1;

double currentMinCost = Double.POSITIVE_INFINITY;

// Loop to find smallest cost v in set V-T

for (int i = 0; i < getSize(); i++)

{

if (!T.contains(i) && cost[i] < currentMinCost)

{

currentMinCost = cost[i];

u = i;

}

}

// Add a new vertex to T and the cost to the total weight

T.add (u);

totalWeight += cost[u];

// Adjust cost[v] for each v that is adjacent to u using

// the weight of the edge (u,v) when v is still in in V-T

for (Edge e : neighbors.get (u))

{

if (!T.contains(e.v) && cost[e.v] > ((WeightedEdge)e).weight)

{

cost[e.v] = ((WeightedEdge)e).weight;

parent[e.v] = u;

}

}

} // End of while

return new MST (startingVertex, parent, T, totalWeight);

}

/** MST is an inner class in WeightedGraph */

public class MST extends Tree

{

// Total weight of all edges in the tree

private double totalWeight;

// Constructor updates parent Tree and sets weight

public MST (int root, int[] parent, List searchOrder,

double totalWeight)

{

super (root, parent, searchOrder);

this.totalWeight = totalWeight;

}

//Return weight of MST

public double getTotalWeight()

{

return totalWeight;

}

}

/** Find single source shortest paths */

public ShortestPathTree getShortestPath (int sourceVertex)

{

// cost[v] stores the cost of the path from v to the source

double[] cost = new double[getSize()];

// Initial cost for each vertice is set to infinity

for (int i = 0; i < cost.length; i++)

{

cost[i] = Double.POSITIVE_INFINITY;

}

// Cost of source is 0

cost[sourceVertex] = 0;

// parent[v] stores the previous vertex of v in the path

int[] parent = new int[getSize()];

// The parent of source is set to -1

parent[sourceVertex] = -1;

// T stores the vertices whose path found so far

List T = new ArrayList<>();

// Expand T

while (T.size() < getSize())

{

// Vertex to be determined

int u = -1;

double currentMinCost = Double.POSITIVE_INFINITY;

// Loop to find smallest cost v in set V-T

for (int i = 0; i < getSize(); i++)

{

if (!T.contains(i) && cost[i] < currentMinCost)

{

currentMinCost = cost[i];

u = i;

}

}

// Add a new vertex to T

T.add (u);

// Adjust cost[v] for v that is adjacent to u

// and v still in set V-T

for (Edge e : neighbors.get (u))

{

if (!T.contains(e.v)

&& cost[e.v] > cost[u] + ((WeightedEdge)e).weight)

{

cost[e.v] = cost[u] + ((WeightedEdge)e).weight;

parent[e.v] = u;

}

}

} // End of while

// Create a ShortestPathTree

return new ShortestPathTree (sourceVertex, parent, T, cost);

}

/** ShortestPathTree is an inner class in WeightedGraph */

public class ShortestPathTree extends Tree

{

private double[] cost; // cost[v] is the cost from v to source

/** Construct a path */

public ShortestPathTree (int source, int[] parent,

List searchOrder, double[] cost)

{

super (source, parent, searchOrder);

this.cost = cost;

}

/** Return the cost for a path from the root to vertex v */

public double getCost (int v)

{

return cost[v];

}

/** Print paths from all vertices to the source */

public String printAllPaths()

{

String str = "";

str += "All shortest paths from " +

vertices.get (getRoot()) + " are: ";

for (int i = 0; i < cost.length; i++)

{

// Print a path from vertex i to the source

str += printPath (i);

str += " (cost: " + Math.round(cost[i]*100)/100.0 + ") "; // Path cost

}

return str;

}

}

}

**********NCCitiesRoads Class**************

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.*;

/**

* The NC Routes Project: The NCCitiesRoads class creates a graph from city and

* road information given to it from a file

*/

public class NCCitiesRoads {

// Static constants for file names

private static final String COMMAND_FILE = ".\\src\\Commands.txt";

private static final String OUTPUT_FILE = ".\\src\\NCRoutesOut.txt";

private static final String NCMAP_FILE = ".\\src\\NCRoadMap.csv";

private static final String NCCITIES_FILE = ".\\src\\NCCities.csv";

// Static constants for file records

private static final String CITY_REC = "CITY";

private static final String ROAD_REC = "ROAD";

// Static data structures to hold the cities, roads, map and such ...

// Holds city name and vertex index pairs to facilitate building roads

private static HashMap cityMap = new HashMap();

private static HashMap citySubMap = new HashMap();

// Holds full map, cities and roads

private static CityRoadMap roadMap = null; // full map, cities and roads

private static List cities = new ArrayList<>(52);

private static List roads = new ArrayList<>(204);

// Holds subset map, cities and roads

private static CityRoadMap subRoadMap = null; // partial map

private static List subCities = new ArrayList<>();

private static List subRoads = new ArrayList<>();

/**

* Create an output PrintWriter file and an input Scanner file Loop through each

* record in the Command File reading the record into a string Split the String

* into an array of Strings at the ':' Pass the array into the processCmd method

* for processing Each of the commands produce output in the form of a String

* This String is sent to the PrintWriter object for output to the file It is

* also sent to std out for display on the console

*/

public static void main(String[] args) throws Exception {

// Create an output File writer

File outFile = new File(OUTPUT_FILE);

PrintWriter writer = new PrintWriter(outFile);

// Create Scanner for reading in Command File

File cmdFile = new File(COMMAND_FILE);

Scanner fin = new Scanner(cmdFile);

String cmdLine = null;

System.out.println("Begin NC Routes Program ");

System.out.println("Input: " + cmdFile.getAbsolutePath() + " ");

// Loop for each line in the Command File and process it

// The command output is placed in the result String

while (fin.hasNext()) {

cmdLine = fin.nextLine();

if (!cmdLine.isEmpty()) {

String cmdArray[] = cmdLine.split(":");

// Each command produces output that is sent to the file

String result = processCmd(cmdArray);

writer.println(result);

System.out.println(result);

}

}

System.out.println(" End NC Routes Program ");

System.out.println(" Output: " + outFile.getAbsolutePath());

writer.close();

fin.close();

}

public static String processCmd(String[] cmdArray) throws Exception {

String city = ""; // Holds starting city name for traversals

String cmd = cmdArray[0].trim();

// Echo the command

String result = "Command: " + cmd + " ";

if (cmd.equalsIgnoreCase("BuildMap")) {

result += buildMap() + " ";

} else if (cmd.equalsIgnoreCase("BuildSubMap")) {

result += buildSubMap() + " ";

} else if (cmd.equalsIgnoreCase("PrintMap")) {

// Code this one liner

} else if (cmd.equalsIgnoreCase("PrintSubMap")) {

// Code this one liner

} else if (cmd.equalsIgnoreCase("PrintCities")) {

// Code this one liner

} else if (cmd.equalsIgnoreCase("PrintSubCities")) {

// Code this one liner

} else if (cmd.equalsIgnoreCase("DFSMap")) {

city = cmdArray[1].trim();

result += dfs(roadMap, cityMap, city);

} else if (cmd.equalsIgnoreCase("DFSSubMap")) {

city = cmdArray[1].trim();

result += dfs(subRoadMap, citySubMap, city);

} else if (cmd.equalsIgnoreCase("BFSMap")) {

city = cmdArray[1].trim();

result += bfs(roadMap, cityMap, city);

} else if (cmd.equalsIgnoreCase("BFSSubMap")) {

city = cmdArray[1].trim();

result += bfs(subRoadMap, citySubMap, city);

} else if (cmd.equalsIgnoreCase("MSTMap")) {

result += mst(roadMap) + " ";

} else if (cmd.equalsIgnoreCase("MSTSubMap")) {

result += mst(subRoadMap) + " ";

} else if (cmd.equalsIgnoreCase("ShortPathMap")) {

city = cmdArray[1].trim();

result += shortestPath(roadMap, cityMap, city) + " ";

} else if (cmd.equalsIgnoreCase("ShortPathSubMap")) {

city = cmdArray[1].trim();

result += shortestPath(subRoadMap, citySubMap, city) + " ";

} else if (cmd.equalsIgnoreCase("SortCities")) {

result += sortCities(cities);

} else {

result += "Unknown command.";

}

return result;

}

/**

* Build CityRoadMap roadMap graph object from the CITY and ROAD records in a

* file

*/

public static String buildMap() throws Exception {

int cityIndex = 0; // City index in cities ArrayList

int roadIndex = 0; // Road index in roads ArrayList

String result = ""; // Message about City and Roads processed

String line = ""; // For reading file record

// Create Scanner for reading in road map information

File mapFile = new File(NCMAP_FILE);

Scanner in = new Scanner(mapFile);

// Loop: Read each line in mapFile:

// First field has either CITY or ROAD to distinguish the record type

// Use nextLine() method to read full record from file

// Use String split method to break up String into comma separated fields

while (in.hasNext()) {

line = in.nextLine();

// Split the CSV file into fields

String fields[] = line.split(",");

// The first field indicates either a City or a Road record

String field1 = fields[0];

// If the first field says "CITY", then create City object

//

// Note: Do NOT round any values (especially GPS) here,

// we want them to have their max precision.

// Only do rounding when displaying values

if (field1.equals(CITY_REC)) {

// City name

String name = fields[1].trim();

// City GPS: longitude (X)

double lon = Double.parseDouble(fields[2].trim());

// City GPS: latitude (Y)

double lat = Double.parseDouble(fields[3].trim());

// City population

int population = Integer.parseInt(fields[4].trim());

// Add City object to Vertex ArrayList

cities.add(new City(name, lon, lat, population, cityIndex));

// Add City name and index to cityMap HashMap

cityMap.put(name, cityIndex);

cityIndex++; // next vertex

}

// If the first field says "ROAD", then create Road object

else if (field1.equals(ROAD_REC)) {

// StartCity name

String startCityName = fields[1].trim();

// EndCity name

String endCityName = fields[2].trim();

// Use cityMap to retrieve vertex index

// and vertex index to retrieve City object

City startCity = cities.get(cityMap.get(startCityName));

City endCity = cities.get(cityMap.get(endCityName));

// Add Road object to Road Edge ArrayList

roads.add(new Road(startCity, endCity));

roadIndex++;

}

}

// Add the processing message to the String result to return

result += "Processed " + cityIndex + " Cities and " + roadIndex + " Roads";

// Close the Scanner

in.close();

// Build a roadMap CityRaodMap graph object of the cities and roads

roadMap = new CityRoadMap(cities, roads);

return result;

}

/**

* Build CityRoadMap subRoadMap graph object from the list of city names in a

* file Review the code from the buildMap method to get started 1. Create

* Scanner 2. Read each line containing a City name a. Use the City name to

* retrieve the City cities index from the cityMap b. Use the City index to

* retrieve the City object from the cities ArrayList c. Set the vertIndex of

* the City object for the subCities ArrayList d. Add the City object to the

* subCities ArrayList e. Add the City name and index to the citySubMap HashMap

* f. Increment cityIndex 3. Find the roads for these cities in the adjacency

* lists for each City which is an ArrayList of WeightedEdge (Roads): Use nested

* loop For each City in the subCities ArrayList, get its adjList from the

* roadMap full graph (getNeighbors method) For each Road in the adjList,

* retrieve the adjacent City Using the City name make sure it is a key in the

* citySubMap If so, then do Set the index of the adjacent City using the

* citySubMap Create a new Road object from the two City objects Add the new

* Road object to the subRoads ArrayList Increment the roadIndex 4. Using the

* subCities ArrayList and the subRoads ArrayList, build a new subRoadMap

* CityRoadMap graph object

*/

public static String buildSubMap() throws Exception

{

// City index in new subCities ArrayList

// This is not the old City index from the full map

int cityIndex = 0;

int newCityIndex = 0;

// Road index in new subRoads ArrayList: used printing message

int roadIndex = 0;

String result = ""; // Message about success

String line = ""; // For reading file record

String cityName = "";

// Create Scanner for reading in the cities

// file (NCCITIES_FILE) for this sub map

File f = new File("C:\\Users\\Chris\\Desktop\\JAVA Projects\\CSC130Project3\\src\\NCCities.csv");

//File f = new File(NCCITIES_FILE);

Scanner in = null;

try

{

in = new Scanner(f);

}

catch (FileNotFoundException e)

{

e.printStackTrace();

}

// Loop Read each record in mapFile:

// Each record should have one City name

// Use nextLine() method, as City names can have more than one word

// Loop begin code goes here

// code goes here

while(in.hasNextLine())

{

// Read each line in mapFile: Each line should have one City name

// code goes here

String currentCity = in.nextLine();

// Grab the city name from the line, trimming whitespace

// code goes here

cityName = currentCity.trim();

//Use the City name to retrieve the City cities index from the cityMap

// Use the cityName as a key into the cityMap to retrieve

// the old City index in the cities ArrayList

// code goes here

cityIndex = cityMap.get(cityName);

//Use the City index to retrieve the City object from the cities ArrayList

// Use the old City index to retrieve the City object

// from the cities ArrayList

// code goes here

City newCity = cities.get(cityIndex);

//Set the vertIndex of the City object for the subCities ArrayList

// Set the new City index of the City object

// in the subCities ArrayList

// code goes here

newCity.setIndex(cityIndex);

//Add the City object to the subCities ArrayList

// Add the City to the subCities ArrayList

// code goes here

subCities.add(newCity);

//Add the City name and index to the citySubMap HashMap

// Add the City name and index to the citySubMap HashMap

// code goes here

citySubMap.put(newCity.getCity(), newCity.getIndex());

// Increment the next new city index

// code goes here

cityIndex++;

// Loop ends

}//while

// Find the roads for these cities in the adjacency lists of the old roadMap graph.

// Skip over the Cities/Roads from the City adjacency lists

// the roads going to cities that are not part of the new subRoadMap

// This requires nested for loops:

// Loop for each City in the subCities ArrayList, grabbing the City object

for (City c: subCities)

{

City tempCity = c;

// Loop code goes here

// Use the City object to retrieve the adjacency list

// containing an ArrayList of adjacent City objects

// Use the CityRoadMap getNeighbors method

// code goes here

ArrayList neighbors = (ArrayList) roadMap.getNeighbors(c);

// Loop for each adjacent City in the adjList, grabbing the City object

for (City n: neighbors)

{

// Loop code goes here

// Retrieve the adjacent City name

// code goes here

City adjCity = n;

// Check the citySubMap to see if the City name is a key

// Use containsKey method

// code goes here

boolean contains = citySubMap.containsKey(n.getCity());

// Use the adjacent City name as a key into the

// citySubMap HashMap to retrieve the new City index

// code goes here

if (contains == true)

{

newCityIndex = citySubMap.get(n.getCity());

}//if

// Set this new index in the adjacent City object

// code goes here

n.setIndex(cityIndex);

// Create a new Road object from the two cities (city and adjCity)

// and add it to the subRoads ArrayList

// code goes here

Road newRoad = new Road(c, n);

subRoads.add(newRoad);

// Increment the Road index

// code goes here

roadIndex++;

// Both Loops end here

}

}

// Add the processing message to the String result to return

result += "Processed " + cityIndex + " Cities and " + roadIndex + " Roads";

// Close the Scanner

in.close();

// Build a graph using the subCities and subRoads

subRoadMap = new CityRoadMap(subCities, subRoads);

return result;

}

/**

* Depth first search: This method follows mostly the same algorithm as in the

* TestDFS class The HashMap is used to retrieve the City index from the passed

* in City name The WeightedGraph (CityRoadMap) methods cannot retrieve the City

* vertex object from the city name.

*/

public static String dfs(CityRoadMap map, HashMap indexMap, String cityName) throws Exception {

String result = ""; // Message to return

// Call the bfs method of the AbstractGraph.Tree class

// passing in the index of the City in the vertices array

AbstractGraph.Tree dfs = map.dfs(indexMap.get(cityName));

// Retrieve the City search order into an ArrayList of indexes

List searchOrders = dfs.getSearchOrder();

// Output the number of Cities found

result += dfs.getNumberOfVerticesFound() + " cities are searched in this DFS order starting from "

+ map.getVertex(searchOrders.get(0)) + " ";

// Loop through the search order ArrayList

// Output each city name: only display 5 cities per line

for (int i = 0; i < searchOrders.size(); i++) {

result += map.getVertex(searchOrders.get(i));

if ((i + 1) % 5 == 0 || i == searchOrders.size() - 1) {

result += ' ';

} else {

result += " : ";

}

}

result += " ";

// Loop through the parent array to display the parent of each City

for (int i = 0; i < searchOrders.size(); i++) {

if (dfs.getParent(i) != -1) {

result += "Parent of " + map.getVertex(i) + " is " + map.getVertex(dfs.getParent(i)) + ' ';

}

}

return result;

}

/**

* Breadth first search: This method follows mostly the same algorithm as in the

* TestBFS class The HashMap is used to retrieve the City index from the passed

* in City name The WeightedGraph (CityRoadMap) methods cannot retrieve the City

* vertex object from the city name.

*/

public static String bfs(CityRoadMap map, HashMap indexMap, String cityName) throws Exception {

String result = ""; // Message to return

// Call the bfs method of the AbstractGraph.Tree class

// passing in the index of the City in the vertices array

AbstractGraph.Tree bfs = map.bfs(indexMap.get(cityName));

// Retrieve the City search order into an ArrayList of indexes

List searchOrders = bfs.getSearchOrder();

// Output the number of Cities found

result += bfs.getNumberOfVerticesFound() + " cities are searched in this BFS order starting from "

+ map.getVertex(searchOrders.get(0)) + " ";

// Loop through the search order ArrayList

// Output each city name: only display 5 cities per line

for (int i = 0; i < searchOrders.size(); i++) {

result += map.getVertex(searchOrders.get(i));

if ((i + 1) % 5 == 0 || i == searchOrders.size() - 1) {

result += ' ';

} else {

result += " : ";

}

}

result += " ";

// Loop through the parent array to display the parent of each City

for (int i = 0; i < searchOrders.size(); i++) {

if (bfs.getParent(i) != -1) {

result += "Parent of " + map.getVertex(i) + " is " + map.getVertex(bfs.getParent(i)) + ' ';

}

}

return result;

}

/**

* Minimum Spanning Tree: Minimum distance Road travel path going through all

* the Cities This method follows mostly the same algorithm as in the

* TestMinimumSpanningTree class

*/

public static String mst(CityRoadMap map) throws Exception {

String result = ""; // Message to return

// Build Minimum Spanning Tree

WeightedGraph.MST tree1 = map.getMinimumSpanningTree();

result += "Total weight is " +

// Output the total weight and the tree

// Round weight to 2 places

Math.round(tree1.getTotalWeight() * 100.0) / 100.0 + " " + tree1.printTree();

return result;

}

/**

* Shortest Path: This method follows mostly the same algorithm as in the

* TestShortestPath class Only code the "AllPaths" piece The HashMap is used to

* retrieve the City index from the passed in City name The WeightedGraph

* (CityRoadMap) methods cannot retrieve the City vertex object from the city

* name.

*/

public static String shortestPath(CityRoadMap map, HashMap indexMap, String fromCityName)

throws Exception {

String result = ""; // Message to return

// Call the getShortestPath method of the WeightedGraph class

// passing in the index of the fromCity in the vertices array

// code goes here

WeightedGraph.ShortestPathTree tree1 = map.getShortestPath(indexMap.get(fromCityName));

// Output all the paths from the fromCity

result = tree1.printAllPaths();

// code goes here

return result;

}

/**

* Sort the cities by population and display them

*/

public static String sortCities(List sortCities) {

String result = ""; // Message to return

// Use the Collections.sort() method to do the sort

// code goes here

Collections.sort(sortCities);

// Loop to output each City object information

// code goes here

for (City c : sortCities) {

result = result + c.toString();

System.out.println(c.toString());

}

return result;

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!