Question

I need Help PLZ ( Java Code ).

Tomorrow 05.06.2019 I have to hand in my homework.

reachability

Actually, you find flying very good, but you do not trust the whole new-fangled flying stuff and the infrastructure it has built up. As a diehard medieval metal fan you prefer to travel from A to B but rather the good old catapult. Since one can not easily take the favorite cat on vacation with it (cats do not get drafts, which is why ICEs are also eliminated), they let themselves be asked to take a plane on vacation. So you are now looking at the network spanned by airports and existing direct connections and wondering which airports are actually critical. A critical airport is an airport whose sudden disappearance would make it impossible to reach all other (remaining) airports from any (remaining) airport. For example, in the following example, the airports ICT and TXL are critical airports, but not BER:

LAS JAV BER IKT! FNJ

So you decide to write a program that will calculate the amount of critical airports for you. You can assume the following assumptions:

At the beginning, all other airports can be reached from any airport.
If a connection from airport
F1 to F2 airport will also consist of a link from F2 airport back to F1.
In the ads.set3.airports package, write a CriticalAirportFinder class and implement the following method:

/ **
* Finds whose removal causes unrealistic destinations. Thus, the
* result must be a set of airports that, if removed, cause at least one pair of
* other airports to have no path between them.
*
* @param airports set of airports.
* @return set of critical airports. Can it be empty?
* airports without a path between them in the input. Must not be
* {@code null}.
* /
public static set findCriticalAirports (Set airports) {
// TODO Implement me!
}

the class Airport:

package ads.set3.airports;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
* Models an airport. For them to be identifiable, all airports have an
* IATA code and
* two airports are considered equal if their IATA codes match. Since this class
* implements {@link #equals(Object)} and {@link #hashCode()}, it can be used in
* hash-based data structures, such as {@link HashSet}.
*
*


* Each airport has a (possibly empty) set of designations that can be reached
* directly (that is, there are direct flights from this airport to all
* designation airports). If there is a direct flight from this airport to
* another airport, there will be a direct return flight as well.
*


*/
public final class Airport implements Comparable {

/** The airport's IATA designation. */
private final String iataDesignation;
/** Set of airports that can be reached from this airport. */
private final Set destinations = new HashSet<>();

/**
* Creates a new airport with no connected airports.
*
* @param iataCode the airport's non-{@code null} IATA designation.
* @throw IllegalArgumentException if the code is invalid.
*/
public Airport(String iataCode) {
ensureValidIataDesignation(iataCode);
this.iataDesignation = iataCode;
}

/**
* Throws an {@link IllegalArgumentException} if the given String is not a valid
* IATA designation.
*/
public static void ensureValidIataDesignation(String iata) {
if (iata == null) {
throw new IllegalArgumentException("IATA code cannot be null.");
}

if (!Pattern.matches("[a-zA-Z]{3}", iata)) {
throw new IllegalArgumentException("IATA codes must consist of three characters.");
}
}

/**
* Returns this airport's IATA designation.
*/
public String getIataDesignation() {
return iataDesignation;
}

/**
* Returns the airport's set of destinations that can be reached directly, to be
* modified at will.
*/
public Set getDestinations() {
return destinations;
}

@Override
public boolean equals(Object obj) {
if (obj instanceof Airport) {
return ((Airport) obj).getIataDesignation().equals(this.getIataDesignation());
} else {
return false;
}
}

@Override
public int hashCode() {
return getIataDesignation().hashCode();
}

@Override
public int compareTo(Airport o) {
return iataDesignation.compareTo(o.iataDesignation);
}

}


I dont have The airport package mentioned.

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

// Import the required classes import java.io.*; import java.util.*; //Create the class public class DPriorityQueue { te memb

/ Find the neighboring node in the file private void FindTheadjacent (String evaluationNode, Root evaluationNodeList) int d -// return the node which has the minimum distance private String getVetex () { priorityQueue.remove ).city; String node retur//Check the node in the file private boolean isThereVertex (List<Root> listofvisitedVertex, String node) for (Root p :Listofv// Start the main method of the program public static void main (String[] arg) throws FileNotFoundException /Declare the variwhile (data.hasMoreTokens ()) timeCost[i] [j++] = data.nextToken (); i++ i -0; /Make tokens of the data of the requestedFligh/Call the DijkstraPriorityQueue to make the priority queue. DPriorityQueue priorityQueue new DPriorityQueue (listofTheNode);

City.java:

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

Root.java:

// Import the required classes import java.util.ArrayList; import java.util.List; // Create the class class Root private List

Sample output:

output.txt:

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

FlightData.txt:

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

Requested.txt:

Dallas |Houston | T Chicago | Dallas IC

Code to copy:

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

Add a comment
Know the answer?
Add Answer to:
I need Help PLZ ( Java Code ). Tomorrow 05.06.2019 I have to hand in my homework. reachability Actually, you find f...
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 need Help PLZ ( Java Code ). Today 14.06.2019 I have to hand in my...

    I need Help PLZ ( Java Code ). Today 14.06.2019 I have to hand in my homework. reachability Actually, you find flying very good, but you do not trust the whole new-fangled flying stuff and the infrastructure it has built up. As a diehard medieval metal fan you prefer to travel from A to B but rather the good old catapult. Since one can not easily take the favorite cat on vacation with it (cats do not get drafts, which...

  • I need help with my homework. The task: Actually, you find flying very good, but you...

    I need help with my homework. The task: Actually, you find flying very good, but you do not trust the whole new-fangled flying stuff and the infrastructure it has built up. As a diehard medieval metal fan you prefer to travel from A to B but rather the good old catapult. Since one can not easily take the favorite cat on vacation with it (cats do not get drafts, which is why ICEs are also eliminated), they let themselves be...

  • This is my code that i need to finish. In BoxRegion.java I have no idea how...

    This is my code that i need to finish. In BoxRegion.java I have no idea how to create the constructor. I tried to use super(x,y) but It is hard to apply. And Also In BoxRegionHashTable, I don't know how to create displayAnnotation BoxRegion.java ------------------------------------------------ public final class BoxRegion { final Point2D p1; final Point2D p2; /** * Create a new 3D point with given x, y and z values * * @param x1, y1 are the x,y coordinates for point...

  • Would someone help please, with code to finish. Iterator and entrySet, I need help. please ```...

    Would someone help please, with code to finish. Iterator and entrySet, I need help. please ``` package coll.MapSet; import java.util.*; public class MapSet extends AbstractMap> implements Iterable { private Map> mapset = new HashMap<>(); /* Implement addValue such that calling this method adds the given value to the HashSet associated with the given key. This method must have the following signature: addValue(K key, V value) */ public void addValue(K key, V value) { // If the set has the key,...

  • I need help with my Java code. A user enters a sentence and the program will...

    I need help with my Java code. A user enters a sentence and the program will tell you what words were duplicated and how many times. If the same word is in the sentence twice, but one is capitalized, it will not count it as a duplicate. How can I make the program read the same word as the same word, even if one is capitalized and the other is not? For example, "the" and "The" should be counted as...

  • (Need to complete the methods and pass a Junit test i can email them to you.)...

    (Need to complete the methods and pass a Junit test i can email them to you.) public class Triangle implements Comparable {    /**    * Stores the number of objects instantiated from the {@code Triangle} class    */    private static int numTriangles;    /**    * The shortest side of the triangle    */    private final double a;    /**    * The side of medium length of the triangle    */    private final double b;...

  • Need help with fixing "TreeMap cannot be resolved to a type" error in code. This was...

    Need help with fixing "TreeMap cannot be resolved to a type" error in code. This was posted in another chegg question but has errors. Was wondering if someone can please fix this. Link to the question asked: https://www.chegg.com/homework-help/questions-and-answers/using-java-import-javautiliterator-import-javautilnosuchelementexception-public-class-pric-q44594716?trackid=undefined I have written the updated code (changes highlighted with green color). The idea is to add a new treemap to priceQueue class to be able to satisfy the asked requirements. Now, if we look at the changes we will need to update...

  • Hello in C#. I need help understanding and knwoing what i missed in my program. The...

    Hello in C#. I need help understanding and knwoing what i missed in my program. The issue is, the program is supposed to have user input for 12 family members and at the end of the 12 it asks for user to input a name to search for. When i put a correct name, it always gives me a relative not found message. WHat did i miss. And can you adjust the new code so im able to see where...

  • I need help with the following Java code Consider a class Fraction of fractions. Each fraction...

    I need help with the following Java code Consider a class Fraction of fractions. Each fraction is signed and has a numerator and a denominator that are integers. Your class should be able to add, subtract, multiply, and divide two fractions. These methods should have a fraction as a parameter and should return the result of the operation as a fraction. The class should also be able to find the reciprocal of a fraction, compare two fractions, decide whether two...

  • Java Programming: Hi, I need help Modifying my code that will throw an IllegalArgumentException. for the...

    Java Programming: Hi, I need help Modifying my code that will throw an IllegalArgumentException. for the following data entry error conditions: A number less than 1 or greater than 12 has been entered for the month A negative integer has been entered for the year utilizes a try and catch clause to display an appropriate message when either of these data entry errors exceptions occur. Thank you let me know if you need more info import java.util.*; //Class definition public...

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