SlideShare a Scribd company logo
1 of 9
Download to read offline
I have compilation errors that I'm struggling with in my code, please can you help me fix the
errors. I'm trying to make a road map, where each place is a vertex and each road between two
places is an edge. Each edge stores a number indicating the length of the road. Assume that there
is at most one road directly connecting two given places, so that there is at most one edge
between two vertices. The map is loaded in via a text file that starts with a line that contains the
number of vertices and the number of edges. After the line mentioned, there are two sections of
content. The initial section holds details regarding the vertices, where each line represents a
single vertex. The information stored for each vertex includes its name and the availability of
charging stations, represented as an integer with 1 indicating availability and 0 indicating
unavailability. The second section stores information about the edges, with each line
corresponding to one edge. Each line contains three numbers: the first two are 0-based indices of
its two incident vertices within the places array; the last number is the edge length. An example
of the map input would look like this as a txt file:
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
private ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
}
// A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map and determine if two places are connnected by a path with
charging stations:");
System.err.println(" java RoadMap -c <MapFile> <StartVertexIndex> <EndVertexIndex>");
System.err.println(" - Load a map and determine the mininmum number of assistance cars
required:");
System.err.println(" java RoadMap -a <MapFile>");
}
public static void main(String[] args) throws Exception {
if (args.length == 2 && args[0].equals("-i")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Error in reading map file");
System.exit(-1);
}
System.out.println();
System.out.println("Read road map from " + args[1] + ":");
map.printMap();
System.out.println();
}
else if (args.length == 2 && args[0].equals("-a")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Error in reading map file");
System.exit(-1);
}
System.out.println();
System.out.println("Read road map from " + args[1] + ":");
map.printMap();
int n = map.minNumAssistanceCars();
System.out.println();
System.out.println("The map requires at least " + n + " assistance car(s)");
System.out.println();
}
else if (args.length == 4 && args[0].equals("-c")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Error in reading map file");
System.exit(-1);
}
System.out.println();
System.out.println("Read road map from " + args[1] + ":");
map.printMap();
int startVertexIdx = -1, endVertexIdx = -1;
try {
startVertexIdx = Integer.parseInt(args[2]);
endVertexIdx = Integer.parseInt(args[3]);
} catch (NumberFormatException e) {
System.err.println("Error: start vertex and end vertex must be specified using their indices");
System.exit(-1);
}
if (startVertexIdx < 0 || startVertexIdx >= map.numPlaces()) {
System.err.println("Error: invalid index for start vertex");
System.exit(-1);
}
if (endVertexIdx < 0 || endVertexIdx >= map.numPlaces()) {
System.err.println("Error: invalid index for end vertex");
System.exit(-1);
}
Vertex startVertex = map.getPlace(startVertexIdx);
Vertex endVertex = map.getPlace(endVertexIdx);
if (!map.isConnectedWithChargingStations(startVertex, endVertex)) {
System.out.println();
System.out.println("There is no path connecting " + map.getPlace(startVertexIdx).getName() + "
and "
+ map.getPlace(endVertexIdx).getName() + " with charging stations");
} else {
System.out.println();
System.out.println("There is at least one path connecting " +
map.getPlace(startVertexIdx).getName() + " and "
+ map.getPlace(endVertexIdx).getName() + " with charging stations");
}
System.out.println();
} else {
printCommandError();
System.exit(-1);
}
}
// Task 1: Load the map from a text file
public void loadMap(String filename) {
File file = new File(filename);
places.clear();
roads.clear();
try {
Scanner sc = new Scanner(file);
// Read the first line: number of vertices and number of edges
int numVertices = sc.nextInt();
int numEdges = sc.nextInt();
for (int i = 0; i < numVertices; ++i) {
// Read the vertex name and its charing station flag
String placeName = sc.next();
int charginStationFlag = sc.nextInt();
boolean hasChargingStataion = (charginStationFlag == 1);
// Add your code here to create a new vertex using the information above and add
// it to places
Vertex vertex = new Vertex(placeName, hasChargingStataion, 0);
places.add(vertex);
}
for (int j = 0; j < numEdges; ++j) {
// Read the edge length and the indices for its two vertices
int vtxIndex1 = sc.nextInt();
int vtxIndex2 = sc.nextInt();
int length = sc.nextInt();
Vertex vtx1 = places.get(vtxIndex1);
Vertex vtx2 = places.get(vtxIndex2);
// Add your code here to create a new edge using the information above and add
// it to roads
// You should also set up incidentRoads for each vertex
Edge edge = new Edge(length, vtx1, vtx2);
roads.add(edge);
// Set up incidentRoads for each vertex
vtx1.incidentRoads.add(edge);
vtx2.incidentRoads.add(edge);
}
sc.close();
// Add your code here if approparite
} catch (Exception e) {
e.printStackTrace();
places.clear();
roads.clear();
}
}
// Task 2: Check if two vertices are connected by a path with charging stations on each
itermediate vertex.
// Return true if such a path exists; return false otherwise.
// The worst-case time complexity of your algorithm should be no worse than O(v + e),
// where v and e are the number of vertices and the number of edges in the graph.
public boolean isConnectedWithChargingStations(Vertex startVertex, Vertex endVertex) {
// Sanity check
if (startVertex.getIndex() == endVertex.getIndex()) {
return true;
}
// The following return statement is just a placeholder.
// Update the code to correctly determine whether the tow vertices are connected by a path with
charing stations
// Initialize a set of visited vertices
Set<Vertex> visited = new HashSet<>();
// Initialize a stack for DFS traversal
Stack<Vertex> stack = new Stack<>();
// Push the starting vertex onto the stack
stack.push(startVertex);
while (!stack.empty()) {
// Pop the top vertex from the stack
Vertex currVertex = stack.pop();
// Check if this vertex has a charging station
if (!currVertex.hasChargingStation()) {
continue;
}
// Check if we've reached the end vertex
if (currVertex.getIndex() == endVertex.getIndex()) {
return true;
}
// Add this vertex to the visited set
visited.add(currVertex);
// Check all the incident roads of this vertex
for (RoadMap road : currVertex.incidentRoads) {
// Get the other vertex connected by this road
Vertex nextVertex = road.getSecondVertex(currVertex);
// Check if we've already visited this vertex
if (visited.contains(nextVertex)) {
continue;
}
// Push this vertex onto the stack
stack.push(nextVertex);
}
}
// We've exhausted all paths and haven't found a path with charging stations
return false;
}
// Task 3: Determine the mininum number of assistance cars required
public int minNumAssistanceCars() {
// Add your code here to compute and return the minimum number of assistance cars required for
this map
int numAssistanceCars = 0;
boolean[] visited = new boolean[numVertices];
for (int i = 0; i < numVertices; i++) {
if (!visited[i]) {
numAssistanceCars++;
bfs(i, visited);
}
}
return numAssistanceCars;
}
private void bfs(int start, boolean[] visited) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(start);
visited[start] = true;
while (!queue.isEmpty()) {
int vertex = queue.poll();
for (int i = 0; i < numVertices; i++) {
if (!visited[i] && adjacencyMatrix[vertex][i] == 1) {
queue.offer(i);
visited[i] = true;
}
}
}
}
public void printMap() {
System.out.println("The map contains " + this.numPlaces() + " places and " + this.numRoads() +
" roads");
System.out.println();
System.out.println("Places:");
for (Vertex v : places) {
System.out.println("- name: " + v.getName() + ", charging station: " + v.hasChargingStation());
}
System.out.println();
System.out.println("Roads:");
for (Edge e : roads) {
System.out.println("- (" + e.getFirstVertex().getName() + ", " + e.getSecondVertex().getName()
+ "), length: " + e.getLength());
}
}
public void printPath(ArrayList<Vertex> path) {
System.out.print("( ");
for (Vertex v : path) {
System.out.print(v.getName() + " ");
}
System.out.println(")");
}
public int numPlaces() {
return places.size();
}
public int numRoads() {
return roads.size();
}
public Vertex getPlace(int idx) {
return places.get(idx);
}
private ArrayList<Vertex> places;
private ArrayList<Edge> roads;
}

More Related Content

Similar to I have compilation errors that I'm struggling with in my code- please.pdf

05 Geographic scripting in uDig - halfway between user and developer
05 Geographic scripting in uDig - halfway between user and developer05 Geographic scripting in uDig - halfway between user and developer
05 Geographic scripting in uDig - halfway between user and developerAndrea Antonello
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdfkamdinrossihoungma74
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfdbrienmhompsonkath75
 
CountryData.cppEDIT THIS ONE#include fstream #include str.pdf
CountryData.cppEDIT THIS ONE#include fstream #include str.pdfCountryData.cppEDIT THIS ONE#include fstream #include str.pdf
CountryData.cppEDIT THIS ONE#include fstream #include str.pdfAggarwalelectronic18
 
Please fill in the code to run the program based on the following in.pdf
Please fill in the code to run the program based on the following in.pdfPlease fill in the code to run the program based on the following in.pdf
Please fill in the code to run the program based on the following in.pdfamarnathmahajansport
 
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docxstudent start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docxhanneloremccaffery
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfadmin463580
 
Need to revise working code below,A good design means the applicat.pdf
Need to revise working code below,A good design means the applicat.pdfNeed to revise working code below,A good design means the applicat.pdf
Need to revise working code below,A good design means the applicat.pdfarchgeetsenterprises
 
Im having trouble figuring out how to code these sections for an a.pdf
Im having trouble figuring out how to code these sections for an a.pdfIm having trouble figuring out how to code these sections for an a.pdf
Im having trouble figuring out how to code these sections for an a.pdfrishteygallery
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
 
3장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_23장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_2suitzero
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdfafgt2012
 
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdfImplementDijkstra’s algorithm using the graph class you implemente.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdfgopalk44
 
Below is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdfBelow is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdfinfo673628
 
ONLY EDIT CapacityOptimizer.java, Simulator.java, and TriangularD.pdf
ONLY EDIT  CapacityOptimizer.java, Simulator.java, and TriangularD.pdfONLY EDIT  CapacityOptimizer.java, Simulator.java, and TriangularD.pdf
ONLY EDIT CapacityOptimizer.java, Simulator.java, and TriangularD.pdfvinodagrawal6699
 
Im looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdfIm looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdfcontact41
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdffms12345
 

Similar to I have compilation errors that I'm struggling with in my code- please.pdf (20)

05 Geographic scripting in uDig - halfway between user and developer
05 Geographic scripting in uDig - halfway between user and developer05 Geographic scripting in uDig - halfway between user and developer
05 Geographic scripting in uDig - halfway between user and developer
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdf
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdf
 
CountryData.cppEDIT THIS ONE#include fstream #include str.pdf
CountryData.cppEDIT THIS ONE#include fstream #include str.pdfCountryData.cppEDIT THIS ONE#include fstream #include str.pdf
CountryData.cppEDIT THIS ONE#include fstream #include str.pdf
 
Please fill in the code to run the program based on the following in.pdf
Please fill in the code to run the program based on the following in.pdfPlease fill in the code to run the program based on the following in.pdf
Please fill in the code to run the program based on the following in.pdf
 
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docxstudent start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdf
 
Need to revise working code below,A good design means the applicat.pdf
Need to revise working code below,A good design means the applicat.pdfNeed to revise working code below,A good design means the applicat.pdf
Need to revise working code below,A good design means the applicat.pdf
 
Im having trouble figuring out how to code these sections for an a.pdf
Im having trouble figuring out how to code these sections for an a.pdfIm having trouble figuring out how to code these sections for an a.pdf
Im having trouble figuring out how to code these sections for an a.pdf
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
3장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_23장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_2
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
 
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdfImplementDijkstra’s algorithm using the graph class you implemente.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
 
Below is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdfBelow is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdf
 
ONLY EDIT CapacityOptimizer.java, Simulator.java, and TriangularD.pdf
ONLY EDIT  CapacityOptimizer.java, Simulator.java, and TriangularD.pdfONLY EDIT  CapacityOptimizer.java, Simulator.java, and TriangularD.pdf
ONLY EDIT CapacityOptimizer.java, Simulator.java, and TriangularD.pdf
 
app.js.docx
app.js.docxapp.js.docx
app.js.docx
 
Im looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdfIm looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdf
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdf
 

More from ColinjHJParsonsa

The organ in the brain that is primarily responsible for normal respir.pdf
The organ in the brain that is primarily responsible for normal respir.pdfThe organ in the brain that is primarily responsible for normal respir.pdf
The organ in the brain that is primarily responsible for normal respir.pdfColinjHJParsonsa
 
The total value of your inventory amounts to $150-000- Your inventory.pdf
The total value of your inventory amounts to $150-000- Your inventory.pdfThe total value of your inventory amounts to $150-000- Your inventory.pdf
The total value of your inventory amounts to $150-000- Your inventory.pdfColinjHJParsonsa
 
The total of individual weights of garbage discarded by 16 households.pdf
The total of individual weights of garbage discarded by 16 households.pdfThe total of individual weights of garbage discarded by 16 households.pdf
The total of individual weights of garbage discarded by 16 households.pdfColinjHJParsonsa
 
The total of individual weights of garbage discarded by 16 households (1).pdf
The total of individual weights of garbage discarded by 16 households (1).pdfThe total of individual weights of garbage discarded by 16 households (1).pdf
The total of individual weights of garbage discarded by 16 households (1).pdfColinjHJParsonsa
 
The Oracle tutorial on Object-Oriented Programming- What is an object-.pdf
The Oracle tutorial on Object-Oriented Programming- What is an object-.pdfThe Oracle tutorial on Object-Oriented Programming- What is an object-.pdf
The Oracle tutorial on Object-Oriented Programming- What is an object-.pdfColinjHJParsonsa
 
The table below shows the orbital period (in AU ) and the distance (in.pdf
The table below shows the orbital period (in AU ) and the distance (in.pdfThe table below shows the orbital period (in AU ) and the distance (in.pdf
The table below shows the orbital period (in AU ) and the distance (in.pdfColinjHJParsonsa
 
The Student Economics Society plans to recruit a new chairperson- Data.pdf
The Student Economics Society plans to recruit a new chairperson- Data.pdfThe Student Economics Society plans to recruit a new chairperson- Data.pdf
The Student Economics Society plans to recruit a new chairperson- Data.pdfColinjHJParsonsa
 
The slope coefficient - is called 1- Alpha 2- Beta 3- Regression 4- In.pdf
The slope coefficient - is called 1- Alpha 2- Beta 3- Regression 4- In.pdfThe slope coefficient - is called 1- Alpha 2- Beta 3- Regression 4- In.pdf
The slope coefficient - is called 1- Alpha 2- Beta 3- Regression 4- In.pdfColinjHJParsonsa
 
The Seven Seas Travel Agency maintains an organized collection of cust.pdf
The Seven Seas Travel Agency maintains an organized collection of cust.pdfThe Seven Seas Travel Agency maintains an organized collection of cust.pdf
The Seven Seas Travel Agency maintains an organized collection of cust.pdfColinjHJParsonsa
 
The Seven Seas Travel Agency maintains an organized collection of cust (1).pdf
The Seven Seas Travel Agency maintains an organized collection of cust (1).pdfThe Seven Seas Travel Agency maintains an organized collection of cust (1).pdf
The Seven Seas Travel Agency maintains an organized collection of cust (1).pdfColinjHJParsonsa
 
The sequence in which different silicate minerals crystallize during t.pdf
The sequence in which different silicate minerals crystallize during t.pdfThe sequence in which different silicate minerals crystallize during t.pdf
The sequence in which different silicate minerals crystallize during t.pdfColinjHJParsonsa
 
The Scientific Method Pre-Labohatory Assignment To be handed in to you.pdf
The Scientific Method Pre-Labohatory Assignment To be handed in to you.pdfThe Scientific Method Pre-Labohatory Assignment To be handed in to you.pdf
The Scientific Method Pre-Labohatory Assignment To be handed in to you.pdfColinjHJParsonsa
 
If W_AA -1-WAB-1-1- and W_BB-1-1- the population size is 10-000 - and.pdf
If W_AA -1-WAB-1-1- and W_BB-1-1- the population size is 10-000 - and.pdfIf W_AA -1-WAB-1-1- and W_BB-1-1- the population size is 10-000 - and.pdf
If W_AA -1-WAB-1-1- and W_BB-1-1- the population size is 10-000 - and.pdfColinjHJParsonsa
 
If we are looking for the probability of event E occurring given that.pdf
If we are looking for the probability of event E occurring given that.pdfIf we are looking for the probability of event E occurring given that.pdf
If we are looking for the probability of event E occurring given that.pdfColinjHJParsonsa
 
If the weather is good- which happens with probability 0-7- Jessica wa.pdf
If the weather is good- which happens with probability 0-7- Jessica wa.pdfIf the weather is good- which happens with probability 0-7- Jessica wa.pdf
If the weather is good- which happens with probability 0-7- Jessica wa.pdfColinjHJParsonsa
 
If the nation's investment opportunities are highly attractive relativ.pdf
If the nation's investment opportunities are highly attractive relativ.pdfIf the nation's investment opportunities are highly attractive relativ.pdf
If the nation's investment opportunities are highly attractive relativ.pdfColinjHJParsonsa
 
If the probability density function of a continuous random variable X.pdf
If the probability density function of a continuous random variable X.pdfIf the probability density function of a continuous random variable X.pdf
If the probability density function of a continuous random variable X.pdfColinjHJParsonsa
 
If the inner lining of the air sacs of birds is neither thin nor highl.pdf
If the inner lining of the air sacs of birds is neither thin nor highl.pdfIf the inner lining of the air sacs of birds is neither thin nor highl.pdf
If the inner lining of the air sacs of birds is neither thin nor highl.pdfColinjHJParsonsa
 
If the partial pressure of oxygen is lower in the pulmonary capillarie.pdf
If the partial pressure of oxygen is lower in the pulmonary capillarie.pdfIf the partial pressure of oxygen is lower in the pulmonary capillarie.pdf
If the partial pressure of oxygen is lower in the pulmonary capillarie.pdfColinjHJParsonsa
 
If the company declares a two-for-one stock split- how many shares are.pdf
If the company declares a two-for-one stock split- how many shares are.pdfIf the company declares a two-for-one stock split- how many shares are.pdf
If the company declares a two-for-one stock split- how many shares are.pdfColinjHJParsonsa
 

More from ColinjHJParsonsa (20)

The organ in the brain that is primarily responsible for normal respir.pdf
The organ in the brain that is primarily responsible for normal respir.pdfThe organ in the brain that is primarily responsible for normal respir.pdf
The organ in the brain that is primarily responsible for normal respir.pdf
 
The total value of your inventory amounts to $150-000- Your inventory.pdf
The total value of your inventory amounts to $150-000- Your inventory.pdfThe total value of your inventory amounts to $150-000- Your inventory.pdf
The total value of your inventory amounts to $150-000- Your inventory.pdf
 
The total of individual weights of garbage discarded by 16 households.pdf
The total of individual weights of garbage discarded by 16 households.pdfThe total of individual weights of garbage discarded by 16 households.pdf
The total of individual weights of garbage discarded by 16 households.pdf
 
The total of individual weights of garbage discarded by 16 households (1).pdf
The total of individual weights of garbage discarded by 16 households (1).pdfThe total of individual weights of garbage discarded by 16 households (1).pdf
The total of individual weights of garbage discarded by 16 households (1).pdf
 
The Oracle tutorial on Object-Oriented Programming- What is an object-.pdf
The Oracle tutorial on Object-Oriented Programming- What is an object-.pdfThe Oracle tutorial on Object-Oriented Programming- What is an object-.pdf
The Oracle tutorial on Object-Oriented Programming- What is an object-.pdf
 
The table below shows the orbital period (in AU ) and the distance (in.pdf
The table below shows the orbital period (in AU ) and the distance (in.pdfThe table below shows the orbital period (in AU ) and the distance (in.pdf
The table below shows the orbital period (in AU ) and the distance (in.pdf
 
The Student Economics Society plans to recruit a new chairperson- Data.pdf
The Student Economics Society plans to recruit a new chairperson- Data.pdfThe Student Economics Society plans to recruit a new chairperson- Data.pdf
The Student Economics Society plans to recruit a new chairperson- Data.pdf
 
The slope coefficient - is called 1- Alpha 2- Beta 3- Regression 4- In.pdf
The slope coefficient - is called 1- Alpha 2- Beta 3- Regression 4- In.pdfThe slope coefficient - is called 1- Alpha 2- Beta 3- Regression 4- In.pdf
The slope coefficient - is called 1- Alpha 2- Beta 3- Regression 4- In.pdf
 
The Seven Seas Travel Agency maintains an organized collection of cust.pdf
The Seven Seas Travel Agency maintains an organized collection of cust.pdfThe Seven Seas Travel Agency maintains an organized collection of cust.pdf
The Seven Seas Travel Agency maintains an organized collection of cust.pdf
 
The Seven Seas Travel Agency maintains an organized collection of cust (1).pdf
The Seven Seas Travel Agency maintains an organized collection of cust (1).pdfThe Seven Seas Travel Agency maintains an organized collection of cust (1).pdf
The Seven Seas Travel Agency maintains an organized collection of cust (1).pdf
 
The sequence in which different silicate minerals crystallize during t.pdf
The sequence in which different silicate minerals crystallize during t.pdfThe sequence in which different silicate minerals crystallize during t.pdf
The sequence in which different silicate minerals crystallize during t.pdf
 
The Scientific Method Pre-Labohatory Assignment To be handed in to you.pdf
The Scientific Method Pre-Labohatory Assignment To be handed in to you.pdfThe Scientific Method Pre-Labohatory Assignment To be handed in to you.pdf
The Scientific Method Pre-Labohatory Assignment To be handed in to you.pdf
 
If W_AA -1-WAB-1-1- and W_BB-1-1- the population size is 10-000 - and.pdf
If W_AA -1-WAB-1-1- and W_BB-1-1- the population size is 10-000 - and.pdfIf W_AA -1-WAB-1-1- and W_BB-1-1- the population size is 10-000 - and.pdf
If W_AA -1-WAB-1-1- and W_BB-1-1- the population size is 10-000 - and.pdf
 
If we are looking for the probability of event E occurring given that.pdf
If we are looking for the probability of event E occurring given that.pdfIf we are looking for the probability of event E occurring given that.pdf
If we are looking for the probability of event E occurring given that.pdf
 
If the weather is good- which happens with probability 0-7- Jessica wa.pdf
If the weather is good- which happens with probability 0-7- Jessica wa.pdfIf the weather is good- which happens with probability 0-7- Jessica wa.pdf
If the weather is good- which happens with probability 0-7- Jessica wa.pdf
 
If the nation's investment opportunities are highly attractive relativ.pdf
If the nation's investment opportunities are highly attractive relativ.pdfIf the nation's investment opportunities are highly attractive relativ.pdf
If the nation's investment opportunities are highly attractive relativ.pdf
 
If the probability density function of a continuous random variable X.pdf
If the probability density function of a continuous random variable X.pdfIf the probability density function of a continuous random variable X.pdf
If the probability density function of a continuous random variable X.pdf
 
If the inner lining of the air sacs of birds is neither thin nor highl.pdf
If the inner lining of the air sacs of birds is neither thin nor highl.pdfIf the inner lining of the air sacs of birds is neither thin nor highl.pdf
If the inner lining of the air sacs of birds is neither thin nor highl.pdf
 
If the partial pressure of oxygen is lower in the pulmonary capillarie.pdf
If the partial pressure of oxygen is lower in the pulmonary capillarie.pdfIf the partial pressure of oxygen is lower in the pulmonary capillarie.pdf
If the partial pressure of oxygen is lower in the pulmonary capillarie.pdf
 
If the company declares a two-for-one stock split- how many shares are.pdf
If the company declares a two-for-one stock split- how many shares are.pdfIf the company declares a two-for-one stock split- how many shares are.pdf
If the company declares a two-for-one stock split- how many shares are.pdf
 

Recently uploaded

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

I have compilation errors that I'm struggling with in my code- please.pdf

  • 1. I have compilation errors that I'm struggling with in my code, please can you help me fix the errors. I'm trying to make a road map, where each place is a vertex and each road between two places is an edge. Each edge stores a number indicating the length of the road. Assume that there is at most one road directly connecting two given places, so that there is at most one edge between two vertices. The map is loaded in via a text file that starts with a line that contains the number of vertices and the number of edges. After the line mentioned, there are two sections of content. The initial section holds details regarding the vertices, where each line represents a single vertex. The information stored for each vertex includes its name and the availability of charging stations, represented as an integer with 1 indicating availability and 0 indicating unavailability. The second section stores information about the edges, with each line corresponding to one edge. Each line contains three numbers: the first two are 0-based indices of its two incident vertices within the places array; the last number is the edge length. An example of the map input would look like this as a txt file: import java.util.*; import java.io.*; class Vertex { // Constructor: set name, chargingStation and index according to given values, // initilaize incidentRoads as empty array public Vertex(String placeName, boolean chargingStationAvailable, int idx) { name = placeName; incidentRoads = new ArrayList<Edge>(); index = idx; chargingStation = chargingStationAvailable; } public String getName() { return name; } public boolean hasChargingStation() { return chargingStation; } public ArrayList<Edge> getIncidentRoads() { return incidentRoads; } // Add a road to the array incidentRoads public void addIncidentRoad(Edge road) { incidentRoads.add(road); }
  • 2. public int getIndex() { return index; } private String name; // Name of the place private ArrayList<Edge> incidentRoads; // Incident edges private boolean chargingStation; // Availability of charging station private int index; // Index of this vertex in the vertex array of the map } class Edge { public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) { length = roadLength; incidentPlaces = new Vertex[] { firstPlace, secondPlace }; } public Vertex getFirstVertex() { return incidentPlaces[0]; } public Vertex getSecondVertex() { return incidentPlaces[1]; } public int getLength() { return length; } private int length; private Vertex[] incidentPlaces; } // A class that represents a sparse matrix public class RoadMap { // Default constructor public RoadMap() { places = new ArrayList<Vertex>(); roads = new ArrayList<Edge>(); } // Auxiliary function that prints out the command syntax public static void printCommandError() { System.err.println("ERROR: use one of the following commands"); System.err.println(" - Load a map and print information:"); System.err.println(" java RoadMap -i <MapFile>");
  • 3. System.err.println(" - Load a map and determine if two places are connnected by a path with charging stations:"); System.err.println(" java RoadMap -c <MapFile> <StartVertexIndex> <EndVertexIndex>"); System.err.println(" - Load a map and determine the mininmum number of assistance cars required:"); System.err.println(" java RoadMap -a <MapFile>"); } public static void main(String[] args) throws Exception { if (args.length == 2 && args[0].equals("-i")) { RoadMap map = new RoadMap(); try { map.loadMap(args[1]); } catch (Exception e) { System.err.println("Error in reading map file"); System.exit(-1); } System.out.println(); System.out.println("Read road map from " + args[1] + ":"); map.printMap(); System.out.println(); } else if (args.length == 2 && args[0].equals("-a")) { RoadMap map = new RoadMap(); try { map.loadMap(args[1]); } catch (Exception e) { System.err.println("Error in reading map file"); System.exit(-1); } System.out.println(); System.out.println("Read road map from " + args[1] + ":"); map.printMap(); int n = map.minNumAssistanceCars(); System.out.println(); System.out.println("The map requires at least " + n + " assistance car(s)"); System.out.println(); } else if (args.length == 4 && args[0].equals("-c")) { RoadMap map = new RoadMap(); try { map.loadMap(args[1]); } catch (Exception e) { System.err.println("Error in reading map file");
  • 4. System.exit(-1); } System.out.println(); System.out.println("Read road map from " + args[1] + ":"); map.printMap(); int startVertexIdx = -1, endVertexIdx = -1; try { startVertexIdx = Integer.parseInt(args[2]); endVertexIdx = Integer.parseInt(args[3]); } catch (NumberFormatException e) { System.err.println("Error: start vertex and end vertex must be specified using their indices"); System.exit(-1); } if (startVertexIdx < 0 || startVertexIdx >= map.numPlaces()) { System.err.println("Error: invalid index for start vertex"); System.exit(-1); } if (endVertexIdx < 0 || endVertexIdx >= map.numPlaces()) { System.err.println("Error: invalid index for end vertex"); System.exit(-1); } Vertex startVertex = map.getPlace(startVertexIdx); Vertex endVertex = map.getPlace(endVertexIdx); if (!map.isConnectedWithChargingStations(startVertex, endVertex)) { System.out.println(); System.out.println("There is no path connecting " + map.getPlace(startVertexIdx).getName() + " and " + map.getPlace(endVertexIdx).getName() + " with charging stations"); } else { System.out.println(); System.out.println("There is at least one path connecting " + map.getPlace(startVertexIdx).getName() + " and " + map.getPlace(endVertexIdx).getName() + " with charging stations"); } System.out.println(); } else { printCommandError(); System.exit(-1); } }
  • 5. // Task 1: Load the map from a text file public void loadMap(String filename) { File file = new File(filename); places.clear(); roads.clear(); try { Scanner sc = new Scanner(file); // Read the first line: number of vertices and number of edges int numVertices = sc.nextInt(); int numEdges = sc.nextInt(); for (int i = 0; i < numVertices; ++i) { // Read the vertex name and its charing station flag String placeName = sc.next(); int charginStationFlag = sc.nextInt(); boolean hasChargingStataion = (charginStationFlag == 1); // Add your code here to create a new vertex using the information above and add // it to places Vertex vertex = new Vertex(placeName, hasChargingStataion, 0); places.add(vertex); } for (int j = 0; j < numEdges; ++j) { // Read the edge length and the indices for its two vertices int vtxIndex1 = sc.nextInt(); int vtxIndex2 = sc.nextInt(); int length = sc.nextInt(); Vertex vtx1 = places.get(vtxIndex1); Vertex vtx2 = places.get(vtxIndex2); // Add your code here to create a new edge using the information above and add // it to roads // You should also set up incidentRoads for each vertex Edge edge = new Edge(length, vtx1, vtx2); roads.add(edge); // Set up incidentRoads for each vertex vtx1.incidentRoads.add(edge); vtx2.incidentRoads.add(edge); } sc.close();
  • 6. // Add your code here if approparite } catch (Exception e) { e.printStackTrace(); places.clear(); roads.clear(); } } // Task 2: Check if two vertices are connected by a path with charging stations on each itermediate vertex. // Return true if such a path exists; return false otherwise. // The worst-case time complexity of your algorithm should be no worse than O(v + e), // where v and e are the number of vertices and the number of edges in the graph. public boolean isConnectedWithChargingStations(Vertex startVertex, Vertex endVertex) { // Sanity check if (startVertex.getIndex() == endVertex.getIndex()) { return true; } // The following return statement is just a placeholder. // Update the code to correctly determine whether the tow vertices are connected by a path with charing stations // Initialize a set of visited vertices Set<Vertex> visited = new HashSet<>(); // Initialize a stack for DFS traversal Stack<Vertex> stack = new Stack<>(); // Push the starting vertex onto the stack stack.push(startVertex); while (!stack.empty()) { // Pop the top vertex from the stack Vertex currVertex = stack.pop(); // Check if this vertex has a charging station if (!currVertex.hasChargingStation()) { continue; } // Check if we've reached the end vertex if (currVertex.getIndex() == endVertex.getIndex()) { return true; }
  • 7. // Add this vertex to the visited set visited.add(currVertex); // Check all the incident roads of this vertex for (RoadMap road : currVertex.incidentRoads) { // Get the other vertex connected by this road Vertex nextVertex = road.getSecondVertex(currVertex); // Check if we've already visited this vertex if (visited.contains(nextVertex)) { continue; } // Push this vertex onto the stack stack.push(nextVertex); } } // We've exhausted all paths and haven't found a path with charging stations return false; } // Task 3: Determine the mininum number of assistance cars required public int minNumAssistanceCars() { // Add your code here to compute and return the minimum number of assistance cars required for this map int numAssistanceCars = 0; boolean[] visited = new boolean[numVertices]; for (int i = 0; i < numVertices; i++) { if (!visited[i]) { numAssistanceCars++; bfs(i, visited); } } return numAssistanceCars; } private void bfs(int start, boolean[] visited) { Queue<Integer> queue = new LinkedList<>(); queue.offer(start); visited[start] = true; while (!queue.isEmpty()) { int vertex = queue.poll();
  • 8. for (int i = 0; i < numVertices; i++) { if (!visited[i] && adjacencyMatrix[vertex][i] == 1) { queue.offer(i); visited[i] = true; } } } } public void printMap() { System.out.println("The map contains " + this.numPlaces() + " places and " + this.numRoads() + " roads"); System.out.println(); System.out.println("Places:"); for (Vertex v : places) { System.out.println("- name: " + v.getName() + ", charging station: " + v.hasChargingStation()); } System.out.println(); System.out.println("Roads:"); for (Edge e : roads) { System.out.println("- (" + e.getFirstVertex().getName() + ", " + e.getSecondVertex().getName() + "), length: " + e.getLength()); } } public void printPath(ArrayList<Vertex> path) { System.out.print("( "); for (Vertex v : path) { System.out.print(v.getName() + " "); } System.out.println(")"); } public int numPlaces() { return places.size(); }
  • 9. public int numRoads() { return roads.size(); } public Vertex getPlace(int idx) { return places.get(idx); } private ArrayList<Vertex> places; private ArrayList<Edge> roads; }