Working code implemented in Java and appropriate comments provided for better understanding:
Here I am attaching code for these 3 files:
package(package name is package):
Source code for Router.java:
public interface Router {
/**
* Value indicating there is no path from the source to
the specified
* destination
*/
int NO_ROUTE = -1;
/**
* Loads the file containing waypoints pairs and the
cost to travel between
* them.
*
* @param routesFilePath path to the routes file
* @param source the waypoint that is the source
location, that is, the
* starting point of all routs
* @throws IllegalArgumentException if the file is not
accessible or the source
* location does not exist
*/
void loadRoutes(String routesFilePath, String
source);
/**
* Returns the route from the designated source
waypoint to the specified
* destination
*
* @param destination endpoint of route
* @return array of waypoints representing the least
expensive route from the
* source to the destination (inclusive). The array is
empty if no path
* exists.
* @throws IllegalArgumentException if destination does
not exist in the route
* file
*/
String[] getRoute(String destination);
/**
* Returns the cost of the shortest route from the
designated source waypoint to
* the specified destination
*
* @param destination endpoint of route from the source
waypoint
* @return the cost in units, or {@link NO_ROUTE} if no
route exists from the
* source to the specified destination
* @throws IllegalArgumentException if destination does
not exist in the route
* file
* @throws NullPointerException if destination is
{@code null}
*/
int getPathCost(String destination);
}
Code Screenshots:
Source code for DroneRouterTest.java:
import static
org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import edu.metrostate.ics340.p3.msr812.DroneRouter;
class DroneRouterTest {
@Test
void test() {
Router router = new
DroneRouter();
router.loadRoutes("routes0.txt",
"A");
assertArrayEquals(new String[] {
"A", "B", "G" }, router.getRoute("G"));
assertEquals(17,
router.getPathCost("G"));
assertThrows(IllegalArgumentException.class, () ->
router.getRoute("Z"));
assertArrayEquals(new String[] {},
router.getRoute("M"));
assertEquals(Router.NO_ROUTE,
router.getPathCost("M"));
}
@Test
void test2() {
Router router = new
DroneRouter();
router.loadRoutes("routes1.txt",
"CHI");
assertArrayEquals(new String[] {
"CHI", "MSP", "DEN", "LAS" }, router.getRoute("LAS"));
assertEquals(2600,
router.getPathCost("DEN"));
assertThrows(IllegalArgumentException.class, () ->
router.getRoute("Z"));
assertArrayEquals(new String[] {},
router.getRoute("STP"));
assertEquals(Router.NO_ROUTE,
router.getPathCost("STP"));
}
}
Code Screenshots:
Source code for DroneRouter.java:
package package;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Scanner;
import java.util.TreeSet;
import package.Router;
/*
* This DroneRouter class implements the Router interface. This
class is
* responsible for interfacing between user command input and with
the Dijsktra
* Algorithm. This class has inner classes of Graph, Edge, and
Vertex.
*/
public class DroneRouter implements Router {
// Saves the Drone starting point.
private String startingPoint;
// Graph array which holds all the paths/edges
private Graph.Edge[] GRAPH = null;
// Constructor for DroneRouter
public DroneRouter() {
}
/*
* Finds absolute file path, use buffered reader to
count lines to instantiate
* the Graph.Edge GRAPH array's length.
*
* Uses scanner to scan each line and create a edges
into Graph.Edge GRAPH
*
* @param routesFilePath path to routing file
*
* @param startingPoint the initial starting point of
the drone
*/
@Override
public void loadRoutes(String routesFilePath, String
startingPoint) {
this.startingPoint =
startingPoint;
String sentence = "";
File file = new
File(routesFilePath).getAbsoluteFile();
BufferedReader reader =
null;
try {
reader = new
BufferedReader(new FileReader(file));
int lines =
0;
while
(reader.readLine() != null)
lines++;
reader.close();
GRAPH = new
Graph.Edge[lines];
} catch (IOException e1) {
throw new
IllegalArgumentException("Illegal Argument Exception, File Not
Found: " + routesFilePath);
}
try {
int counter =
0;
Scanner input =
new Scanner(file);
while
(input.hasNextLine()) {
sentence = input.nextLine();
String[] values = sentence.split("\\s+");
GRAPH[counter] = new Graph.Edge(values[0],
values[1], Integer.parseInt(values[2]));
counter++;
}
input.close();
} catch (FileNotFoundException
e) {
e.printStackTrace();
}
}
/*
* Finds route. Creates an instance of Graph with the
provided Graph.Edge GRAPH
* made by routing file. Runes the dijkstra algorithm
in respect to the starting
* point given iniitally.
*
* @param destination to find path to.
*/
@Override
public String[] getRoute(String destination) {
Graph g = new Graph(GRAPH);
g.dijkstra(startingPoint);
return
g.printPath(destination);
}
/*
* Finds cost. Creates an instance of Graph with the
provided Graph.Edge GRAPH
* made by routing file. Runes the dijkstra algorithm
in respect to the starting
* point given iniitally.
*
* @param destination to find path to.
*/
@Override
public int getPathCost(String destination) {
Graph g = new Graph(GRAPH);
g.dijkstra(startingPoint);
return
g.printCost(destination);
}
}
class Graph {
// mapping of vertex names to Vertex objects, built
from a set of Edges
private final Map<String, Vertex> graph;
private static ArrayList<String> temp = new
ArrayList<String>();
private static int cost = 0;
/**
* One edge of the graph (only used by Graph
constructor)
*/
public static class Edge {
public final String source,
destination;
public final int weight;
public Edge(String source,
String destination, int weight) {
this.source =
source;
this.destination
= destination;
this.weight =
weight;
}
}
/**
* One vertex of the graph, with mappings of
neighboring vertexes
*/
public static class Vertex implements
Comparable<Vertex> {
public final String name;
// MAX_VALUE assumed to be
infinity
public int weight =
Integer.MAX_VALUE;
public Vertex previous =
null;
public final Map<Vertex,
Integer> neighbours = new HashMap<>();
public Vertex(String name)
{
this.name =
name;
}
/*
* Will traverse and calculate which
paths are taken to get from source to
* destination. Will add the
node/edge to a temp arraylist. Arraylist is
* converted to array and
returned.
*
* Will return an empty array if
null edge.
*/
private String[] printPath() {
if (this ==
this.previous) {
temp.add(this.name);
} else if
(this.previous == null) {
String[] emptyArray = new String[0];
return emptyArray;
} else {
this.previous.printPath();
temp.add(this.name);
}
String[] path =
new String[temp.size()];
path =
temp.toArray(path);
return
path;
}
/*
* Will traverse and calculate which
costs are taken to get from source to
* destination. Will add the
node/edge to a running tally.
*
* Will return -1 if null.
*/
private int printCost() {
if (this ==
this.previous) {
cost += this.weight;
} else if
(this.previous == null) {
return Router.NO_ROUTE;
} else {
this.previous.printPath();
cost += this.weight;
}
return
cost;
}
public int compareTo(Vertex
other) {
if (weight ==
other.weight)
return name.compareTo(other.name);
return
Integer.compare(weight, other.weight);
}
}
/**
* Builds a graph from a set of edges
*/
public Graph(Edge[] edges) {
graph = new
HashMap<>(edges.length);
// one pass to find all
vertices
for (Edge e : edges) {
if
(!graph.containsKey(e.source))
graph.put(e.source, new Vertex(e.source));
if
(!graph.containsKey(e.destination))
graph.put(e.destination, new
Vertex(e.destination));
}
// another pass to set
neighbouring vertices
for (Edge e : edges) {
graph.get(e.source).neighbours.put(graph.get(e.destination),
e.weight);
//
graph.get(e.destination).neighbours.put(graph.get(e.source),
e.weight); //
// also do this
for
// an undirected
graph
}
}
/**
* Runs dijkstras algorithm with the startPoint
specified earlier.
*
* @param startingPoint the vertex to start on.
*/
public void dijkstra(String startingPoint) {
if
(!graph.containsKey(startingPoint)) {
throw new
IllegalArgumentException("Illegal Argument Exception on value: " +
startingPoint);
}
final Vertex source =
graph.get(startingPoint);
NavigableSet<Vertex> q = new
TreeSet<>();
// set-up vertices
for (Vertex v : graph.values())
{
v.previous = v
== source ? source : null;
v.weight = v ==
source ? 0 : Integer.MAX_VALUE;
q.add(v);
}
dijkstra(q);
}
/**
* Implementation of dijkstra's algorithm using a
binary heap.
*/
private void dijkstra(final NavigableSet<Vertex>
q) {
Vertex u, v;
while (!q.isEmpty()) {
// vertex with
shortest weightance (first iteration will return source)
u =
q.pollFirst();
if (u.weight ==
Integer.MAX_VALUE)
break; // we can ignore u (and any other
remaining vertices) since they are unreachable
// look at
weightances to each neighbour
for
(Map.Entry<Vertex, Integer> a : u.neighbours.entrySet())
{
v = a.getKey(); // the neighbour in this
iteration
final int alternateDist = u.weight +
a.getValue();
if (alternateDist < v.weight) { // shorter
path to neighbour found
q.remove(v);
v.weight =
alternateDist;
v.previous = u;
q.add(v);
}
}
}
}
/**
* Helper method to get the path of the vertices taken
from stratingPoint to
* destination
*
* @param destination
* @return array
*/
public String[] printPath(String destination) {
if
(!graph.containsKey(destination)) {
throw new
IllegalArgumentException("Invalid Destination, " +
destination);
} else {
Graph.temp = new
ArrayList<String>();
return
graph.get(destination).printPath();
}
}
/**
* Helper method to get the cost of the vertices taken
from stratingPoint to
* destination
*
* @param destination
* @return cost
*/
public int printCost(String destination) {
if
(!graph.containsKey(destination)) {
throw new
IllegalArgumentException("Invalid Destination, " +
destination);
} else {
Graph.cost =
0;
return
graph.get(destination).printCost();
}
}
}
Code Screenshots:
Input Files:
routes0.txt:
A B 5
B C 10
B G 12
G C 5
C D 15
C E 2
D F 4
G E 2
E F 2
A E 3
L M 10
routes1.txt:
CHI MSP 2400
DEN LAS 1400
NYC DZS 8300
STP MSP 30
LAS DZS 200
NYC CHI 100
MSP DEN 200
Input Screenshots:
Note: Output is None, besides method return values. That's why I am not uploading any output for this problem.
Hope it helps, if you like the answer give it a thumbs up. Thank you.
the class is supoose to implement the provided interface Router implemement the methods as per the...
Given the Interface Code write a java class that implements this interface and show the working functionality in the main method: public interface CustomList<T> { /** * This method should add a new item into the <code>CustomList</code> and should * return <code>true</code> if it was successfully able to insert an item. * @param item the item to be added to the <code>CustomList</code> * @return <code>true</code> if item was successfully added, <code>false</code> if the item was not successfully added (note: it...
package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic * collection to store elements where indexes represent priorities and the * priorities can change in several ways. * * This collection class uses an Object[] data structure to store elements. * * @param <E> The type of all elements stored in this collection */ // You will have an error until you have have all methods // specified in interface PriorityList included inside this...
Lab Assignment : In this lab, you are going to implement QueueADT interface that defines a queue. Then you are going to use the queue to store animals. 1. Write a LinkedQueue class that implements the QueueADT.java interface using links. 2. Textbook implementation uses a count variable to keep track of the elements in the queue. Don't use variable count in your implementation (points will be deducted if you use instance variable count). You may use a local integer variable...
In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> { /** Adds one element to the top of this stack. * @param element element to be pushed onto stack */ public void push (T element); /** Removes and returns the top element from this stack. * @return T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. * @return T...
Implement a class CSVReader that reads a CSV file, and provide methods: int numbOfRows() int numberOfFields(int row) String field(int row, int column) Please use the CSVReader and CSVReaderTester class to complete the code. I have my own CSV files and cannot copy them to here. So if possible, just use a random CSV file. CSVReader.java import java.util.ArrayList; import java.util.Scanner; import java.io.*; /** Class to read and process the contents of a standard CSV file */ public class CSVReader {...
How to complete this methods: import java.io.FileInputStream; import java.io.FileNotFoundException; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; /** * Utility class that deals with all the other classes. * * @author EECS2030 Summer 2019 * */ public final class Registrar { public static final String COURSES_FILE = "Courses.csv"; public static final String STUDENTS_FILE = "Students.csv"; public static final String PATH = System.getProperty("java.class.path"); /** * Hash table to store the list of students using their...
DO NOT COPY AND PASTED!!!!!!!!!!!!! IF YOU DO NOT HOW TO DO IT, JUST DO NOT ANSWER MY QUESTIONS package scheduler; import java.util.List; public class Scheduler { /** * Instantiates a new, empty scheduler. */ public Scheduler() { } /** * Adds a course to the scheduler. * * @param course the course to be added */ public void addCourse(Course course) { } /** * Returns the list of courses that this scheduler knows about. * * This returned object...
In a file named LLBag.java, write a class called LLBag that implements the Bag interface using a linked list instead of an array. You may use a linked list with or without a dummy head node. Bag interface code: /* * Bag.java * * Computer Science 112, Boston University */ /* * An interface for a Bag ADT. */ public interface Bag { /* * adds the specified item to the Bag. Returns true on success * and...
PLEASE HURRY Software Testing Don't make any changes to the provided code. Please write a test case for the below prompt using the provided java programs Use the setString() function in MyCustomStringInterface to set the value to “Peter Piper picked a peck of pickled peppers.”. Then test to see if reverseNCharacters() function returns the reversed string when the characters are reversed in groups of 4 and padding is disabled (in this case, “etePiP r repkcipa decep fo kcip delkpep srep.”)....
How to complete these methods: /** * Returns a reference to the course with title equals to the argument. This * method searches in the courses stored in the HashMap {@code courses} to find * the course whose title equals to the argument {@code title}. If the course is * not found, {@code null} is returned. * * @param title the title of the course * @return a reference to the course, or {@code null} if the course is not ...