Question

The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java....

The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks.

DPriorityQueue.java:


// Import the required classes
import java.io.*;
import java.util.*;

//Create the class
public class DPriorityQueue
{
//Declare the private members variables.
private int type1,type2;
private String CostInTime[][], SVertex, DVertex;
private List<String> listOfTheNodes;
private Set<String> List;
private List<Root> ListOfVisitedNode;
private HashMap<String, Integer> minimalDistance;
private HashMap<String, Integer> distOfVertices;
private PriorityQueue<City> priorityQueue;

// prove the definition of the function to create priority queue of the nodes
public DPriorityQueue(List<String> listOfTheNodes)
{   
  this.listOfTheNodes = listOfTheNodes;
  minimalDistance = new HashMap<String,Integer>();
  distOfVertices = new HashMap<String,Integer>();
  List = new HashSet<String>();
  ListOfVisitedNode = new ArrayList<Root>();
  priorityQueue = new PriorityQueue<City>(new City());      
}

// Find the neighboring node in the file
private void FindTheadjacent(String evaluationNode, Root evaluationNodeList)
{
  int d = -1;
  int newd = -1;

  for (int i = 0; i<CostInTime.length; i++)
  {
   if(!CostInTime[i][0].equals(evaluationNode))
    continue;
   String target;
   for (int j = 0; j < listOfTheNodes.size(); j++)
   {
    target = listOfTheNodes.get(j);
    if(!CostInTime[i][1].equals(target))
     continue;
    if (!List.contains(target))
    {
     d = Integer.parseInt(CostInTime[i][type1]);
     newd = minimalDistance.get(evaluationNode) + d;
     if (newd < minimalDistance.get(target))
     {
      minimalDistance.replace(target,newd);
      distOfVertices.replace(target,distOfVertices.get(evaluationNode) +
        Integer.parseInt(CostInTime[i][type2]));
      for (Root path : ListOfVisitedNode)
      {
       if(path.exists(target))
        path.delete(target);
       break;
      }
      evaluationNodeList.add(target);
     }
     priorityQueue.add(new City(target,minimalDistance.get(target)));
    }  
   }
  }
}

// return the node which has the minimum distance
private String getVetex()
{
  String node = priorityQueue.remove().city;
  return node;
}

// Dijkstra,s algorithm definition
public void dijkastra(String costInTime[][], String requiredPath[])
{
  String vartexEvaluation;
  SVertex = requiredPath[0];
  DVertex = requiredPath[1];
  if(requiredPath[2].equalsIgnoreCase("C"))
  {
   type1 = 2;
   type2 = 3;
  }
  else
  {
   type1 = 3;
   type2 = 2;
  }


  this.CostInTime = costInTime;


  for (String vertex:listOfTheNodes)
  {
   minimalDistance.put(vertex, Integer.MAX_VALUE);
   distOfVertices.put(vertex, Integer.MAX_VALUE);
  }

  priorityQueue.add(new City(SVertex, 0));
  minimalDistance.replace(SVertex,0);
  distOfVertices.replace(SVertex, 0);
  while (!priorityQueue.isEmpty())
  {
   vartexEvaluation = getVetex();
   Root evaluationNodeList = new Root();
   evaluationNodeList.setNode(vartexEvaluation);
   List.add(vartexEvaluation);
   FindTheadjacent(vartexEvaluation, evaluationNodeList);
   if(!isThereVertex(ListOfVisitedNode, vartexEvaluation))
    ListOfVisitedNode.add(evaluationNodeList);
  }
}
// Check the node in the file
private boolean isThereVertex(List<Root> listOfVisitedVertex, String node)
{
  for (Root p : ListOfVisitedNode)
  {
   if(p.getNode().equals(node))
    return true;
  }
  return false;
}

// Find the destination node in the file to complete the path.
private static List<String> PathofTheRoot(List<Root> visitedCity, String target)
{
  List<String> completePath = new ArrayList<String>();
  for( Root path : visitedCity)
  {
   if(!path.exists(target))
    continue;
   completePath = PathofTheRoot(visitedCity, path.getNode());
   completePath.add(target);
   return completePath;
  }
  completePath.add(target);
  return completePath;
}

// Start the main method of the program
public static void main(String[] arg) throws FileNotFoundException
{
  //Declare the variables.
  String timeCost[][],PathList[][];
  BufferedReader dataOfTheFlight, requestedData;
  List<String> listOfTheNode;
  PrintWriter out = new PrintWriter("output1.txt");

  try
  {
   // Read the data from the files
   dataOfTheFlight = new BufferedReader(new FileReader("FlightData1.txt"));
   requestedData = new BufferedReader(new FileReader("Requested.txt"));

   String string;

   listOfTheNode = new ArrayList<String>();
   timeCost = new String[Integer.parseInt(dataOfTheFlight.readLine())][4];
   PathList = new String[Integer.parseInt(requestedData.readLine())][3];

   int i=0,j; String _node;

   // Make tokens of the data of the flightData file
   while((string = dataOfTheFlight.readLine()) != null)
   {
    j=0;
    StringTokenizer data = new StringTokenizer(string,"|");
    int k = 1;
    while(k<=2)
    {
     if(!listOfTheNode.contains(_node = data.nextToken()))
     {
      timeCost[i][j++] = _node;
      listOfTheNode.add(_node);
     }
     else
      timeCost[i][j++] = _node;
     k++;
    }

    while(data.hasMoreTokens())
    {
     timeCost[i][j++] = data.nextToken();
    }
    i++;         
   }
   i=0;

   // Make tokens of the data of the requestedFlightData file
   while((string = requestedData.readLine()) != null)
   {
    j=0;
    StringTokenizer data = new StringTokenizer(string,"|");
    while(data.hasMoreTokens())       
     PathList[i][j++] = data.nextToken();
    i++;         
   }       

   i=1;

   // Check the type of the cost
   for(String requsetedPath[] : PathList)
   {
    if(!(listOfTheNode.contains(requsetedPath[0])&& listOfTheNode.contains(requsetedPath[1])))
    {
     out.println("Path can not be find !!!!!");
     continue;
    }
    String _type,_otherType;

    if(requsetedPath[2].equals("T"))
    {
     _type = "Time";
     _otherType = "Cost";
    }

    else
    {
     _type = "Cost";
     _otherType = "Time";
    }

    // Call the DijkstraPriorityQueue to make the priority queue.
    DPriorityQueue priorityQueue = new DPriorityQueue(listOfTheNode);

    // Call the dijkstra_algorithm method to run the Dijkstra's algorithm
    priorityQueue.dijkastra(timeCost, requsetedPath);

    out.println("Flight "+i+": "+priorityQueue.SVertex+", "+
      priorityQueue.DVertex+" ("+_type+")");
    for (String vertex:listOfTheNode)
    {
     if(!vertex.equals(priorityQueue.DVertex))
      continue;
     List<String> list = PathofTheRoot(priorityQueue.ListOfVisitedNode,
       priorityQueue.DVertex);
     for (int k = 0; k < list.size(); k++)
     {
      if(k == list.size()-1 )
       out.print(list.get(k)+". ");
      else
       out.print(list.get(k)+" --> ");
     }                  
     out.println(_type+": " + priorityQueue.minimalDistance.get(vertex)+" "
       +_otherType+": "+priorityQueue.distOfVertices.get(vertex));
     break;
    }
    i++;
   }

  } catch (Exception e)
  {
   System.out.println("Exception has occured:" + e.toString());
  }
  out.close();
}
}

City.java:

//Import the class Comparator
import java.util.Comparator;
// Class
class City implements Comparator<City>
{
public String city;
public int cost;

public City()
{
}

// Compare the nodes.
@Override
public int compare(City node1, City node2)
{
  if (node1.cost < node2.cost)
   return -1;
  if (node1.cost > node2.cost)
   return 1;
  return 0;
}

public City(String city, int cost)
{
  this.city = city;
  this.cost = cost;
}
}

Root.java:


// Import the required classes
import java.util.ArrayList;
import java.util.List;
// Create the class
class Root
{
private List<String> root;
private String city;
// Get the node
public String getNode()
{
  return this.city;
}
// Add the node in the array List
public void add(String city)
{
  root.add(city);
}
//Delete the node from the list
public void delete(String city)
{
  root.remove(city);
}
// Check if the node exist or not
public Boolean exists(String city)
{
  if(root.contains(city))
   return true;
  return false;
}
//Create the arrayList
public Root()
{
  root = new ArrayList<String>();
}
// Set the node
public void setNode(String Node)
{
  this.city = Node;
}
}

FlightData1.txt

7
Dallas|Austin|98|47
Austin|Houston|95|39
Dallas|Houston|101|51
Austin|Chicago|144|192
Chicago|Austin|155|200
Austin|Dallas|100|50
Houston|Dallas|100|50

Requested.txt:

2
Dallas|Houston|T
Chicago|Dallas|C

0 0
Add a comment Improve this question Transcribed image text
Answer #1

--------------------------DPriorityQueue.java-------------------------

// Import the required classes

import java.io.*;

import java.util.*;

//Create the class

public class DPriorityQueue

{

//Declare the private members variables.

private int type1,type2;

private String CostInTime[][], SVertex, DVertex;

private List<String> listOfTheNodes;

private Set<String> List;

private List<Root> ListOfVisitedNode;

private HashMap<String, Integer> minimalDistance;

private HashMap<String, Integer> distOfVertices;

private PriorityQueue<City> priorityQueue;

// prove the definition of the function to create priority queue of the nodes

public DPriorityQueue(List<String> listOfTheNodes)

{  

this.listOfTheNodes = listOfTheNodes;

minimalDistance = new HashMap<String,Integer>();

distOfVertices = new HashMap<String,Integer>();

List = new HashSet<String>();

ListOfVisitedNode = new ArrayList<Root>();

priorityQueue = new PriorityQueue<City>(new City());     

}

// Find the neighboring node in the file

private void FindTheadjacent(String evaluationNode, Root evaluationNodeList)

{

int d = -1;

int newd = -1;

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

{

   if(!CostInTime[i][0].equals(evaluationNode))

    continue;

   String target;

   for (int j = 0; j < listOfTheNodes.size(); j++)

   {

    target = listOfTheNodes.get(j);

    if(!CostInTime[i][1].equals(target))

     continue;

    if (!List.contains(target))

    {

     d = Integer.parseInt(CostInTime[i][type1]);

     newd = minimalDistance.get(evaluationNode) + d;

     if (newd < minimalDistance.get(target))

     {

      minimalDistance.replace(target,newd);

      distOfVertices.replace(target,distOfVertices.get(evaluationNode) +

        Integer.parseInt(CostInTime[i][type2]));

      for (Root path : ListOfVisitedNode)

      {

       if(path.exists(target))

        path.delete(target);

       break;

      }

      evaluationNodeList.add(target);

     }

     priorityQueue.add(new City(target,minimalDistance.get(target)));

    }

   }

}

}

// return the node which has the minimum distance

private String getVetex()

{

String node = priorityQueue.remove().city;

return node;

}

// Dijkstra,s algorithm definition

public void dijkastra(String costInTime[][], String requiredPath[])

{

String vartexEvaluation;

SVertex = requiredPath[0];

DVertex = requiredPath[1];

if(requiredPath[2].equalsIgnoreCase("C"))

{

   type1 = 2;

   type2 = 3;

}

else

{

   type1 = 3;

   type2 = 2;

}

this.CostInTime = costInTime;

for (String vertex:listOfTheNodes)

{

   minimalDistance.put(vertex, Integer.MAX_VALUE);

   distOfVertices.put(vertex, Integer.MAX_VALUE);

}

priorityQueue.add(new City(SVertex, 0));

minimalDistance.replace(SVertex,0);

distOfVertices.replace(SVertex, 0);

while (!priorityQueue.isEmpty())

{

   vartexEvaluation = getVetex();

   Root evaluationNodeList = new Root();

   evaluationNodeList.setNode(vartexEvaluation);

   List.add(vartexEvaluation);

   FindTheadjacent(vartexEvaluation, evaluationNodeList);

   if(!isThereVertex(ListOfVisitedNode, vartexEvaluation))

    ListOfVisitedNode.add(evaluationNodeList);

}

}

// Check the node in the file

private boolean isThereVertex(List<Root> listOfVisitedVertex, String node)

{

for (Root p : ListOfVisitedNode)

{

   if(p.getNode().equals(node))

    return true;

}

return false;

}

// Find the destination node in the file to complete the path.

private static List<String> PathofTheRoot(List<Root> visitedCity, String target)

{

List<String> completePath = new ArrayList<String>();

for( Root path : visitedCity)

{

   if(!path.exists(target))

    continue;

   completePath = PathofTheRoot(visitedCity, path.getNode());

   completePath.add(target);

   return completePath;

}

completePath.add(target);

return completePath;

}

// Start the main method of the program

public static void main(String[] arg) throws FileNotFoundException

{

    if( arg.length < 3 )

    {

        System.out.println("Error! Insufficient arguments");

        System.exit(0);

    }

   

//Declare the variables.

String timeCost[][],PathList[][];

BufferedReader dataOfTheFlight, requestedData;

List<String> listOfTheNode;

// PrintWriter out = new PrintWriter("output1.txt");

// set the file name with third command line argument

PrintWriter out = new PrintWriter(arg[2]);

try

{

   // Read the data from the files

   // dataOfTheFlight = new BufferedReader(new FileReader("FlightData1.txt"));

  

   // set the file name with first command line argument

   dataOfTheFlight = new BufferedReader(new FileReader(arg[0]));

  

   // requestedData = new BufferedReader(new FileReader("Requested.txt"));

  

   // set the file name with second command line argument

   requestedData = new BufferedReader(new FileReader(arg[1]));

   String string;

   listOfTheNode = new ArrayList<String>();

   timeCost = new String[Integer.parseInt(dataOfTheFlight.readLine())][4];

   PathList = new String[Integer.parseInt(requestedData.readLine())][3];

   int i=0,j; String _node;

   // Make tokens of the data of the flightData file

   while((string = dataOfTheFlight.readLine()) != null)

   {

    j=0;

    StringTokenizer data = new StringTokenizer(string,"|");

    int k = 1;

    while(k<=2)

    {

     if(!listOfTheNode.contains(_node = data.nextToken()))

     {

      timeCost[i][j++] = _node;

      listOfTheNode.add(_node);

     }

     else

      timeCost[i][j++] = _node;

     k++;

    }

    while(data.hasMoreTokens())

    {

     timeCost[i][j++] = data.nextToken();

    }

    i++;        

   }

   i=0;

   // Make tokens of the data of the requestedFlightData file

   while((string = requestedData.readLine()) != null)

   {

    j=0;

    StringTokenizer data = new StringTokenizer(string,"|");

    while(data.hasMoreTokens())      

     PathList[i][j++] = data.nextToken();

    i++;        

   }      

   i=1;

   // Check the type of the cost

   for(String requsetedPath[] : PathList)

   {

    if(!(listOfTheNode.contains(requsetedPath[0])&& listOfTheNode.contains(requsetedPath[1])))

    {

     out.println("Path can not be find !!!!!");

     continue;

    }

    String _type,_otherType;

    if(requsetedPath[2].equals("T"))

    {

     _type = "Time";

     _otherType = "Cost";

    }

    else

    {

     _type = "Cost";

     _otherType = "Time";

    }

    // Call the DijkstraPriorityQueue to make the priority queue.

    DPriorityQueue priorityQueue = new DPriorityQueue(listOfTheNode);

    // Call the dijkstra_algorithm method to run the Dijkstra's algorithm

    priorityQueue.dijkastra(timeCost, requsetedPath);

    out.println("Flight "+i+": "+priorityQueue.SVertex+", "+

      priorityQueue.DVertex+" ("+_type+")");

    for (String vertex:listOfTheNode)

    {

     if(!vertex.equals(priorityQueue.DVertex))

      continue;

     List<String> list = PathofTheRoot(priorityQueue.ListOfVisitedNode,

       priorityQueue.DVertex);

     for (int k = 0; k < list.size(); k++)

     {

      if(k == list.size()-1 )

       out.print(list.get(k)+". ");

      else

       out.print(list.get(k)+" --> ");

     }                 

     out.println(_type+": " + priorityQueue.minimalDistance.get(vertex)+" "

       +_otherType+": "+priorityQueue.distOfVertices.get(vertex));

     break;

    }

    i++;

   }

} catch (Exception e)

{

   System.out.println("Exception has occured:" + e.toString());

}

out.close();

}

}

City.java:

//Import the class Comparator
import java.util.Comparator;
// Class
class City implements Comparator<City>
{
public String city;
public int cost;

public City()
{
}

// Compare the nodes.
@Override
public int compare(City node1, City node2)
{
  if (node1.cost < node2.cost)
   return -1;
  if (node1.cost > node2.cost)
   return 1;
  return 0;
}

public City(String city, int cost)
{
  this.city = city;
  this.cost = cost;
}
}

Root.java:


// Import the required classes
import java.util.ArrayList;
import java.util.List;
// Create the class
class Root
{
private List<String> root;
private String city;
// Get the node
public String getNode()
{
  return this.city;
}
// Add the node in the array List
public void add(String city)
{
  root.add(city);
}
//Delete the node from the list
public void delete(String city)
{
  root.remove(city);
}
// Check if the node exist or not
public Boolean exists(String city)
{
  if(root.contains(city))
   return true;
  return false;
}
//Create the arrayList
public Root()
{
  root = new ArrayList<String>();
}
// Set the node
public void setNode(String Node)
{
  this.city = Node;
}
}

FlightData1.txt

7
Dallas|Austin|98|47
Austin|Houston|95|39
Dallas|Houston|101|51
Austin|Chicago|144|192
Chicago|Austin|155|200
Austin|Dallas|100|50
Houston|Dallas|100|50

Requested.txt:

2
Dallas|Houston|T
Chicago|Dallas|C

Sample Output

:Users RishablDesktop>javac DPriorityQueue.java C:\Users Rishab \Desktop>java DPriorityQueue FlightData1.txt Requested.txt ou

---------------------Output1.txt-------------------

Flight 1: Dallas, Houston (Time)
Dallas --> Houston. Time: 51 Cost: 101
Flight 2: Chicago, Dallas (Cost)
Chicago --> Austin --> Dallas. Cost: 255 Time: 250

Add a comment
Know the answer?
Add Answer to:
The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am getting this Error can you please fix my Java code. import java.awt.Dialog; import java.awt.Label;...

    I am getting this Error can you please fix my Java code. import java.awt.Dialog; import java.awt.Label; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Fall_2017 {    public TextArea courseInput;    public Label textAreaLabel;    public JButton addData;    public Dialog confirmDialog;    HashMap<Integer, ArrayList<String>> students;    public Fall_2017(){    courseInput = new TextArea(20, 40);    textAreaLabel = new Label("Student's data:");    addData = new JButton("Add...

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import...

    Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Provides an implementation of a binary search tree * with no balance constraints, implemented with linked nodes. * * * */ public class Bst<T extends Comparable<T>> implements Iterable<T> { ////////////////////////////////////////////////////////////////// // I M P L E M E N T T H E M I N M E T H O D B E L O W...

  • Please Modify TestPart2 to test the correctness and efficiency of FasterDefaultList. Thanks import java.util.List; import java.util.AbstractList;...

    Please Modify TestPart2 to test the correctness and efficiency of FasterDefaultList. Thanks import java.util.List; import java.util.AbstractList; import java.util.Map; import java.util.HashMap; public class DumbDefaultList<T> extends AbstractList<T> { Map<Integer,T> map; public DumbDefaultList() { map = new HashMap<Integer,T>(); } public int size() { return Integer.MAX_VALUE; } public T get(int i) { return map.get(i); } public T set(int i, T x) { return map.put(i, x); } public void add(int i, T x) { Map<Integer, T> map2 = new HashMap<Integer,T>(); for (Integer k : map.keySet())...

  • (Reading & Writing Business Objects) I need to have my Classes be able to talk to...

    (Reading & Writing Business Objects) I need to have my Classes be able to talk to Files. How do I make it such that I can look in a File for an account number and I am able to pull up all the details? The file should be delimited by colons (":"). The Code for testing 'Select' that goes in main is: Account a1 = new Account(); a1.select(“90001”); a1.display(); Below is what it should look like for accounts 90000:3003:SAV:8855.90 &...

  • What is the output of the following program? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class...

    What is the output of the following program? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Test implements Comparable<Test> private String[] cast; public Test( String[] st) cast = st; public int compareTo( Test t) if ( cast.length >t.cast.length ) t return +1; else if cast.length < t.cast.length return -1; else return 0; public static void main( String[] args String[] a"Peter", "Paul", "Mary" String[] b_ { "Мое", ''Larry", "Curly", String [ ] c = { ·Mickey", "Donald" }; "Shemp" }; List<Test>...

  • This is the question: These are in Java format. Comments are required on these two Classes...

    This is the question: These are in Java format. Comments are required on these two Classes (Student.java and StudentDemo.java) all over the coding: Provide proper comments all over the codings. --------------------------------------------------------------------------------------------------------------- import java.io.*; import java.util.*; class Student {    private String name;    private double gradePointAverage;    public Student(String n , double a){    name = n;    gradePointAverage = a;    }    public String getName(){ return name;    }    public double getGradePointAverage(){ return gradePointAverage;    }   ...

  • Can anyone helps to create a Test.java for the following classes please? Where the Test.java will...

    Can anyone helps to create a Test.java for the following classes please? Where the Test.java will have a Scanner roster = new Scanner(new FileReader(“roster.txt”); will be needed in this main method to read the roster.txt. public interface List {    public int size();    public boolean isEmpty();    public Object get(int i) throws OutOfRangeException;    public void set(int i, Object e) throws OutOfRangeException;    public void add(int i, Object e) throws OutOfRangeException; public Object remove(int i) throws OutOfRangeException;    } public class ArrayList implements List {   ...

  • JAVA: How do I output all the data included for each employee? I can only get...

    JAVA: How do I output all the data included for each employee? I can only get it to output the name, monthly salary and annual salary, but only from the Employee.java file, not Salesman.java or Executive.java. Employee.java package project1; public class Employee { private String name; private int monthlySalary; public Employee(String name, int monthlySalary) { this.name = name; this.monthlySalary = monthlySalary; } public int getAnnualSalary() { int totalPay = 0; totalPay = 12 * monthlySalary; return totalPay; } public String...

  • I've previously completed a Java assignment where I wrote a program that reads a given text...

    I've previously completed a Java assignment where I wrote a program that reads a given text file and creates an index that stores the line numbers for where individual words occur. I've been given a new assignment where I need to modify some of my old code. I need to replace the indexer in my Index class with a NavigableMap<String, Word> and update my Word class with NavigableSet<Integer> lines. The instantiated objects should be TreeMap() and TreeSet(). I have below...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT