SlideShare a Scribd company logo
Can you please debug this? Thank you in advance! This program is supposed to use stacks and
find the paths of an airplane. It should tell you whether or not the plane goes from the requested
city to the requested destination. requestFile.txt contains the requests, flightFile.txt contains the
flights and cityFile.txt contains the city's that the airline serves.
My errors: my output is simply "Hpair does not serve Los Angeles." Thats it and it stops.
It should look something like (these are not real values of the file just an example):
"Request is to fly from cityA to CityB.
Hpair flight from cityA to CityB.
Request is to fly from cityC to cityD.
Sorry, HPAir does not serve City D
Request is to fly from cityE to CityF
Sorry, HPAir does not fly from cityE to CityF"
**It said to use ispath.cpp but I got confused on how to implement it completely."
isPath.cpp
//***I did not include ispath.cpp in my program. Parts of it are in the map.h portion.
main.cpp
#include
#include
#include "Map.h"
using namespace std;
int main()
{
Map aMap;
aMap.readFlights();
aMap.verifyRequestedFile();
}
StackInterface.h
#ifndef StackInterface_h
#define StackInterface_h
template
class StackInterface
{
/** Checks if the stack is empty.
@return True if the stack is empty or false if the stack is not.*/
virtual bool isEmpty() const = 0;
/** Adds a new item to the stack
@post newEntry is at the top of the stack
@param newEntry is the object to be added to the stack
@return True if successfully added, otherwise false. */
virtual bool push(const ItemType& newEntry) = 0;
/** Removes item from stack
@post The top item in the stack is removed
@return True if the item was removed, false if it was not. */
virtual bool pop() = 0;
/** Returns the top item in the stack
@pre The stack is not empty
@post The top item in the stack is returned
@return The top of the stack */
virtual ItemType peek() const = 0;
};
#endif /* StackInterface_h */
Node.h
#ifndef node_h
#define node_h
template
class Node {
public:
Node();
Node (const ItemType &anItem);
Node(const ItemType &anItem, Node * nextNodePtr);
void setItem(const ItemType &anItem);
void setNext(Node * nextNodePtr);
ItemType getItem() const;
Node* getNext() const;
private:
ItemType item;
Node* next;
};
template
Node::Node():next(nullptr){}
template
Node::Node(const ItemType &anItem):item(anItem), next(nullptr){}
template
Node::Node(const ItemType &anItem, Node * nextNodePtr):item(anItem), next(nextNodePtr)
{
}
template
void Node::setItem(const ItemType &anItem){
item = anItem;
}
template
void Node::setNext(Node * nextNodePtr) {
next = nextNodePtr;
}
template
ItemType Node::getItem() const {
return item;
}
template
Node* Node::getNext()const{
return next;
}
#endif /* node_h */
LinkedStack.h
#include
#ifndef LinkedStack_h
#define LinkedStack_h
#include "Node.h"
#include "StackInterface.h"
template
class LinkedStack:public StackInterface{
public:
LinkedStack();
LinkedStack(const LinkedStack &aStack); //space matter?***********
virtual ~LinkedStack();
bool isEmpty() const;
bool push(const ItemType &newItem);
bool pop();
ItemType peek() const;
private:
Node* topPtr;
};
template
LinkedStack::LinkedStack() : topPtr(nullptr)
{
}
template
LinkedStack::LinkedStack(const LinkedStack &aStack)
{
Node* origChainPtr = aStack->topPtr;
if (origChainPtr == nullptr)
topPtr = nullptr;
else
{
topPtr = new Node();
topPtr->setItem(origChainPtr->getItem());
/**Points to the last node in the new chain
*/
Node* newChainPtr = topPtr;
while (origChainPtr != nullptr)
{
origChainPtr = origChainPtr->getNext();
ItemType nextItem = origChainPtr->getItem();
Node* newNodePtr = new Node(nextItem);
newChainPtr->setNext(newNodePtr);
newChainPtr = newChainPtr->getNext();
}
newChainPtr->setNext(nullptr);
}
}
/**destructor
*/
template
LinkedStack::~LinkedStack()
{
//pops until the stack is empty
while (!isEmpty())
pop();
}
/**isEmpty
*/
template
bool LinkedStack::isEmpty() const
{
return topPtr == nullptr;
}
/**Push
**/
template
bool LinkedStack::push(const ItemType &newItem)
{
Node* newNodePtr = new Node(newItem, topPtr);
topPtr = newNodePtr;
newNodePtr = nullptr;
return true;
}
template
bool LinkedStack::pop()
{
bool result = false;
/* If stack is not empty delete the top item
*/
if (!isEmpty())
{
Node * nodeToDeletePtr = topPtr;
topPtr = topPtr->getNext();
//returns deleted node to the system
nodeToDeletePtr->setNext(nullptr);
delete nodeToDeletePtr;
nodeToDeletePtr = nullptr;
result = true;
} //end if
return result;
} //end pop
template
ItemType LinkedStack::peek() const
{
assert (!isEmpty()); //Enforces precondition
return topPtr->getItem();
}
#endif /* LinkedStack_h */
Map.h
#ifndef Map_h
#define Map_h
#include
#include "LinkedStack.h"
#include "City.h"
#include
#include
using namespace std;
template
class Map
{
public:
void readFlights();
void addToHead(City&anOriginCity, City&aDestinationCity);
void verifyRequestedFile();
bool isPath(City&flightCity, City&RequestedCity);
private:
vector>cityVector;
LinkedStack>stackCity;
CitynotCity;
};
template
bool Map::isPath(City &flightCity, City &requestedCity)
{
bool result, done;
City*requestedPtr = new City(requestedCity);
for (City *tempPtr = flightCity.headPtr;
tempPtr != 0;
tempPtr = tempPtr->headPtr)
{
if (tempPtr->destinationCity == requestedPtr->destinationCity)
{
done = true;
return done;
}
}
done = false;
return done;
}
template
void Map::verifyRequestedFile()
{
fstream requestedRoutes;
string originCity, destinationCity;
bool doesNotMatch;
bool correctPath;
requestedRoutes.open("RequestFile.txt", ios::in);
char test;
if (requestedRoutes.is_open())
{
while (!requestedRoutes.eof())
{
getline(requestedRoutes, originCity, ','); //switched values, so switch back
requestedRoutes.get(test);
while (requestedRoutes.peek() == 't')
{
requestedRoutes.get(test);
}
getline(requestedRoutes, destinationCity, ' ');
doesNotMatch = false;
for (int i = 0; i < cityVector.size(); i++)
{
if (cityVector[i].getOriginCity() == originCity)
{
doesNotMatch = true;
notCity.setOriginCity(originCity);
notCity.setDestinationCity(destinationCity);
correctPath = isPath(cityVector[i], notCity);
if (correctPath)
cout << "HPair serves from " << originCity << " to " << destinationCity << endl;
else
cout << "HPair does NOT serve from " << originCity << " to " << destinationCity << endl;
}
}
if (!doesNotMatch)
cout << "HPair does not serve " << originCity << endl;
}
}
}
template
void Map::addToHead(City &anOriginCity, City &aDestinationCity)
{
City* newOne = new City(aDestinationCity);
City* newSecond = new City(anOriginCity);
if (anOriginCity.headPtr == 0)
{
anOriginCity.headPtr = newOne;
}
else
{
newOne->headPtr = anOriginCity.headPtr;
anOriginCity.headPtr = newOne;
}
}
template
void Map::readFlights()
{
fstream readCities, readFlights;
City aCity;
string originCity, destinationCity;
char test;
readCities.open("CityFile.txt", ios::in);
if (readCities.is_open())
while (!readCities.eof())
while (getline(readCities, originCity))
{
aCity.setOriginCity(originCity);
cityVector.push_back(aCity);
}
for (int i = 0; i < cityVector.size(); i++)
readCities.close();
readFlights.open("FlightFile.txt", ios::in);
if (readFlights.is_open())
{
while (!readFlights.eof())
{
getline(readFlights, originCity, ',');
readFlights.get(test);
while (readFlights.peek() == 't')
{
readFlights.get(test);
}
getline(readFlights, destinationCity, ' ');
for (int i = 0; i < cityVector.size(); i++)
{
if (cityVector[i].getOriginCity() == originCity)
{
notCity.setOriginCity(originCity);
notCity.setDestinationCity(destinationCity);
addToHead(cityVector[i], notCity);
stackCity.push(notCity);
}
}
}
}
readFlights.close();
}
#endif /* Map_h */
City.h
#ifndef City_h
#define City_h
#include
#include
using namespace std;
template
class City
{
public:
string originCity;
string destinationCity;
City *headPtr;
City();
City(string origin, string destination);
City(const City &aCity);
void setOriginCity(string aCityOrigin);
void setDestinationCity(string aCityDestination);
string getOriginCity();
string getDestinationCity();
void displayOriginCity();
};
template
City::City()
{
originCity = " ";
destinationCity = " ";
headPtr = 0;
}
template
City::City(string origin, string destination)
{
originCity = origin;
destinationCity = destination;
}
template
City::City(const City &aCity)
{
this->originCity = aCity.originCity;
this->destinationCity = aCity.destinationCity;
this->headPtr = aCity.headPtr;
}
template
void City::setOriginCity(string aCityOrigin)
{
this->originCity = aCityOrigin;
}
template
void City::setDestinationCity(string aCityDestination)
{
this->destinationCity = aCityDestination;
}
template
void City::displayOriginCity()
{
cout << this->originCity << endl;
}
template
string City::getOriginCity()
{
return (this->originCity);
}
template
string City::getDestinationCity()
{
return(this->destinationCity);
}
#endif /* City_h */
requestFile.txt
Los Angeles, Houston
Glendale, Houston
Dallas, Austin
Cleveland, Chicago
Indianapolis, San Francisco
San Francisco, Washington
Boston, Columbia
Miami, Denver
flightFile.txt
Atlanta, Chicago
Boise, Chicago
Boston, Chicago
Chicago, Atlanta
Chicago, Boise
Chicago, Boston
Chicago, Houston
Cleveland, Houston
Columbia, Houston
Dallas, Houston
Denton, Houston
Denver, Houston
Houston, Glendale
Houston, Cleveland
Houston, Columbia
Houston, Dallas
Houston, Denton
Houston, Denver
Houston, Chicago
Indianapolis, Los Angeles
Los Angeles, Indianapolis
Miami, Los Angeles
Miami, Atlanta
Atlanta, Miami
Los Angeles, Miami
San Francisco, Los Angeles
Los Angeles, San Francisco
Tampa, Los Angeles
Los Angeles, Tampa
Washington, Los Angeles
Los Angeles, Washington
cityFile.txt
Atlanta
Austin
Boise
Boston
Buffalo
Chicago
Cincinnati
Cleveland
Columbia
Dallas
Denton
Denver
Detroit
Everett
Glendale
Honolulu
Houston
Indianapolis
Irvine
Los Angeles
Miami
Nashville
Oakland
Reno
Salt Lake City
San Francisco
Tampa
Washington
Solution
class GraphFindAllPaths implements Iterable { /* A map from nodes in the graph to sets of
outgoing edges. Each * set of edges is represented by a map from edges to doubles. */
private final Map> graph = new HashMap>(); /** * Adds a new node to the graph. If the
node already exists then its a * no-op. * * @param node Adds to a graph. If node is
null then this is a no-op. * @return true if node is added, false otherwise. */ public
boolean addNode(T node) { if (node == null) { throw new
NullPointerException("The input node cannot be null."); } if
(graph.containsKey(node)) return false; graph.put(node, new HashMap()); return true;
} /** * Given the source and destination node it would add an arc from source * to
destination node. If an arc already exists then the value would be * updated the new value.
* * @param source the source node. * @param destination the
destination node. * @param length if length if * @throws
NullPointerException if source or destination is null. * @throws NoSuchElementException
if either source of destination does not exists. */ public void addEdge (T source, T
destination, double length) { if (source == null || destination == null) { throw new
NullPointerException("Source and Destination, both should be non-null."); } if
(!graph.containsKey(source) || !graph.containsKey(destination)) { throw new
NoSuchElementException("Source and Destination, both should be part of graph"); }
/* A node would always be added so no point returning true or false */
graph.get(source).put(destination, length); } /** * Removes an edge from the graph.
* * @param source If the source node. * @param destination If the destination
node. * @throws NullPointerException if either source or destination specified is null *
@throws NoSuchElementException if graph does not contain either source or destination */
public void removeEdge (T source, T destination) { if (source == null || destination ==
null) { throw new NullPointerException("Source and Destination, both should be non-
null."); } if (!graph.containsKey(source) || !graph.containsKey(destination)) {
throw new NoSuchElementException("Source and Destination, both should be part of graph");
} graph.get(source).remove(destination); } /** * Given a node, returns the
edges going outward that node, * as an immutable map. * * @param node The node
whose edges should be queried. * @return An immutable view of the edges leaving that node.
* @throws NullPointerException If input node is null. * @throws
NoSuchElementException If node is not in graph. */ public Map edgesFrom(T node) {
if (node == null) { throw new NullPointerException("The node should not be null.");
} Map edges = graph.get(node); if (edges == null) { throw new
NoSuchElementException("Source node does not exist."); } return
Collections.unmodifiableMap(edges); } /** * Returns the iterator that travels the nodes
of a graph. * * @return an iterator that travels the nodes of a graph. */ @Override
public Iterator iterator() { return graph.keySet().iterator(); } } /** * Given a connected
directed graph, find all paths between any two input points. */ public class FindAllPaths {
private final GraphFindAllPaths graph; /** * Takes in a graph. This graph should not be
changed by the client */ public FindAllPaths(GraphFindAllPaths graph) { if (graph ==
null) { throw new NullPointerException("The input graph cannot be null."); }
this.graph = graph; } private void validate (T source, T destination) { if (source ==
null) { throw new NullPointerException("The source: " + source + " cannot be null.");
} if (destination == null) { throw new NullPointerException("The destination:
" + destination + " cannot be null."); } if (source.equals(destination)) { throw
new IllegalArgumentException("The source and destination: " + source + " cannot be the
same."); } } /** * Returns the list of paths, where path itself is a list of nodes. *
* @param source the source node * @param destination the destination node
* @return List of all paths */ public List> getAllPaths(T source, T destination) {
validate(source, destination); List> paths = new ArrayList>(); recursive(source,
destination, paths, new LinkedHashSet()); return paths; } // so far this dude ignore's
cycles. private void recursive (T current, T destination, List> paths, LinkedHashSet path) {
path.add(current); if (current == destination) { paths.add(new ArrayList(path));
path.remove(current); return; } final Set edges =
graph.edgesFrom(current).keySet(); for (T t : edges) { if (!path.contains(t)) {
recursive (t, destination, paths, path); } } path.remove(current); }
public static void main(String[] args) { GraphFindAllPaths graphFindAllPaths = new
GraphFindAllPaths(); graphFindAllPaths.addNode("A");
graphFindAllPaths.addNode("B"); graphFindAllPaths.addNode("C");
graphFindAllPaths.addNode("D"); graphFindAllPaths.addEdge("A", "B", 10);
graphFindAllPaths.addEdge("A", "C", 10); graphFindAllPaths.addEdge("B", "D",
10); graphFindAllPaths.addEdge("C", "D", 10); graphFindAllPaths.addEdge("B",
"C", 10); graphFindAllPaths.addEdge("C", "B", 10); FindAllPaths findAllPaths =
new FindAllPaths(graphFindAllPaths); List> paths = new ArrayList>(); // ABD
List path1 = new ArrayList(); path1.add("A"); path1.add("B"); path1.add("D"); //
ABCD List path2 = new ArrayList(); path2.add("A"); path2.add("B");
path2.add("C"); path2.add("D"); //ACD List path3 = new ArrayList();
path3.add("A"); path3.add("C"); path3.add("D"); //ABCD List path4 = new
ArrayList(); path4.add("A"); path4.add("C"); path4.add("B"); path4.add("D");
paths.add(path1); paths.add(path2); paths.add(path3); paths.add(path4);
findAllPaths.getAllPaths("A", "D"); assertEquals(paths, findAllPaths.getAllPaths("A",
"D")); } }

More Related Content

DOCX
@author Derek Harter @cwid 123 45 678 @class .docx
PDF
Hi,you covered mostly things.there are issue to point and link poi.pdf
PDF
Write a program that converts an infix expression into an equivalent.pdf
PDF
Header file for an array-based implementation of the ADT bag. @f.pdf
PDF
Write a class that implements the BagInterface. BagInterface should .pdf
PDF
#include iostream #include fstream #include iomanip #.pdf
DOCX
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
DOCX
#include iostream#include string#include fstreamusi.docx
@author Derek Harter @cwid 123 45 678 @class .docx
Hi,you covered mostly things.there are issue to point and link poi.pdf
Write a program that converts an infix expression into an equivalent.pdf
Header file for an array-based implementation of the ADT bag. @f.pdf
Write a class that implements the BagInterface. BagInterface should .pdf
#include iostream #include fstream #include iomanip #.pdf
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
#include iostream#include string#include fstreamusi.docx

Similar to Can you please debug this Thank you in advance! This program is sup.pdf (20)

PPTX
Basic C++ 11/14 for Python Programmers
PDF
#include iostream #include fstream #include cstdlib #.pdf
PDF
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
PDF
#include iostream #includeData.h #includePerson.h#in.pdf
PDF
Computer Investgatort Project (HOTEL MANAGEMENT SYSTEM)
PDF
ItemNodeh include ltiostreamgt include ltstring.pdf
PPTX
DS Assignment Presentation 20242024.pptx
PDF
implement the ListLinked ADT (the declaration is given in ListLinked.pdf
DOCX
ECS 40 Program #1 (50 points, my time 2.5 hours) .docx
PDF
Use the code below from the previous assignment that we need to exte.pdf
PDF
include ltfunctionalgt include ltiteratorgt inclu.pdf
PDF
Basic c++ 11/14 for python programmers
PDF
So here is the code from the previous assignment that we need to ext.pdf
PDF
How do you stop infinite loop Because I believe that it is making a.pdf
PPTX
Stack and its applications
PDF
The STL
PDF
I have the following code and I need to know why I am receiving the .pdf
PDF
DS & Algo 1 - C++ and STL Introduction
PDF
Object Oriented Programming (OOP) using C++ - Lecture 5
Basic C++ 11/14 for Python Programmers
#include iostream #include fstream #include cstdlib #.pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
#include iostream #includeData.h #includePerson.h#in.pdf
Computer Investgatort Project (HOTEL MANAGEMENT SYSTEM)
ItemNodeh include ltiostreamgt include ltstring.pdf
DS Assignment Presentation 20242024.pptx
implement the ListLinked ADT (the declaration is given in ListLinked.pdf
ECS 40 Program #1 (50 points, my time 2.5 hours) .docx
Use the code below from the previous assignment that we need to exte.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdf
Basic c++ 11/14 for python programmers
So here is the code from the previous assignment that we need to ext.pdf
How do you stop infinite loop Because I believe that it is making a.pdf
Stack and its applications
The STL
I have the following code and I need to know why I am receiving the .pdf
DS & Algo 1 - C++ and STL Introduction
Object Oriented Programming (OOP) using C++ - Lecture 5

More from FashionBoutiquedelhi (20)

PDF
Questions1) How does multimedia transmission differ than messag.pdf
PDF
Question 1 of 10 Map sapling learning Based on the chart to the right.pdf
PDF
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdf
PDF
On January 1, 2002, Germany officially adopted the euro as its curre.pdf
PDF
Networking problem help Consider the following TCP session between h.pdf
PDF
Lipid bilayers can only be synthesized by biological organisms. This .pdf
PDF
Is a neutral trait (meaning it is neither deleterious nor advantageo.pdf
PDF
Let T R^n rightarrow R^m be a linear transformation. Given a subspa.pdf
PDF
Just a general question on some vocab words I cannot piece together .pdf
PDF
In order to be useful to managers, management accounting reports shou.pdf
PDF
Im also confused on question 9 and 10 On which point(s) would Charle.pdf
PDF
In about six billion years, our suns luminosity (a.k.a. power outpu.pdf
PDF
I have to write a java program . So basically I have to take my in.pdf
PDF
Fill in the blanks.Intensity of orangebrownred color of reduced .pdf
PDF
Explain how cellular respiration (O2 consumption and CO2 production).pdf
PDF
Entrepreneurship isA. one of the basic rights of the private enter.pdf
PDF
Discrete Random Variables we are working with commonly used discre.pdf
PDF
Determine the open intervals over which the function is increasing an.pdf
PDF
Discuss and define Isotropy. Anisotropy and Orthotropy with regards t.pdf
PDF
Consider the circuits in figure 2.32. If we assume the transistors ar.pdf
Questions1) How does multimedia transmission differ than messag.pdf
Question 1 of 10 Map sapling learning Based on the chart to the right.pdf
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdf
On January 1, 2002, Germany officially adopted the euro as its curre.pdf
Networking problem help Consider the following TCP session between h.pdf
Lipid bilayers can only be synthesized by biological organisms. This .pdf
Is a neutral trait (meaning it is neither deleterious nor advantageo.pdf
Let T R^n rightarrow R^m be a linear transformation. Given a subspa.pdf
Just a general question on some vocab words I cannot piece together .pdf
In order to be useful to managers, management accounting reports shou.pdf
Im also confused on question 9 and 10 On which point(s) would Charle.pdf
In about six billion years, our suns luminosity (a.k.a. power outpu.pdf
I have to write a java program . So basically I have to take my in.pdf
Fill in the blanks.Intensity of orangebrownred color of reduced .pdf
Explain how cellular respiration (O2 consumption and CO2 production).pdf
Entrepreneurship isA. one of the basic rights of the private enter.pdf
Discrete Random Variables we are working with commonly used discre.pdf
Determine the open intervals over which the function is increasing an.pdf
Discuss and define Isotropy. Anisotropy and Orthotropy with regards t.pdf
Consider the circuits in figure 2.32. If we assume the transistors ar.pdf

Recently uploaded (20)

PPTX
Cell Types and Its function , kingdom of life
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Classroom Observation Tools for Teachers
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Cell Structure & Organelles in detailed.
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Complications of Minimal Access Surgery at WLH
PPTX
master seminar digital applications in india
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Sports Quiz easy sports quiz sports quiz
PDF
RMMM.pdf make it easy to upload and study
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Cell Types and Its function , kingdom of life
Renaissance Architecture: A Journey from Faith to Humanism
human mycosis Human fungal infections are called human mycosis..pptx
Microbial disease of the cardiovascular and lymphatic systems
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
VCE English Exam - Section C Student Revision Booklet
Classroom Observation Tools for Teachers
Microbial diseases, their pathogenesis and prophylaxis
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Cell Structure & Organelles in detailed.
Supply Chain Operations Speaking Notes -ICLT Program
Computing-Curriculum for Schools in Ghana
Final Presentation General Medicine 03-08-2024.pptx
Complications of Minimal Access Surgery at WLH
master seminar digital applications in india
Anesthesia in Laparoscopic Surgery in India
Module 4: Burden of Disease Tutorial Slides S2 2025
Sports Quiz easy sports quiz sports quiz
RMMM.pdf make it easy to upload and study
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf

Can you please debug this Thank you in advance! This program is sup.pdf

  • 1. Can you please debug this? Thank you in advance! This program is supposed to use stacks and find the paths of an airplane. It should tell you whether or not the plane goes from the requested city to the requested destination. requestFile.txt contains the requests, flightFile.txt contains the flights and cityFile.txt contains the city's that the airline serves. My errors: my output is simply "Hpair does not serve Los Angeles." Thats it and it stops. It should look something like (these are not real values of the file just an example): "Request is to fly from cityA to CityB. Hpair flight from cityA to CityB. Request is to fly from cityC to cityD. Sorry, HPAir does not serve City D Request is to fly from cityE to CityF Sorry, HPAir does not fly from cityE to CityF" **It said to use ispath.cpp but I got confused on how to implement it completely." isPath.cpp //***I did not include ispath.cpp in my program. Parts of it are in the map.h portion. main.cpp #include #include #include "Map.h" using namespace std; int main() { Map aMap; aMap.readFlights(); aMap.verifyRequestedFile(); } StackInterface.h #ifndef StackInterface_h #define StackInterface_h template class StackInterface {
  • 2. /** Checks if the stack is empty. @return True if the stack is empty or false if the stack is not.*/ virtual bool isEmpty() const = 0; /** Adds a new item to the stack @post newEntry is at the top of the stack @param newEntry is the object to be added to the stack @return True if successfully added, otherwise false. */ virtual bool push(const ItemType& newEntry) = 0; /** Removes item from stack @post The top item in the stack is removed @return True if the item was removed, false if it was not. */ virtual bool pop() = 0; /** Returns the top item in the stack @pre The stack is not empty @post The top item in the stack is returned @return The top of the stack */ virtual ItemType peek() const = 0; }; #endif /* StackInterface_h */ Node.h #ifndef node_h #define node_h template class Node { public: Node(); Node (const ItemType &anItem); Node(const ItemType &anItem, Node * nextNodePtr); void setItem(const ItemType &anItem); void setNext(Node * nextNodePtr); ItemType getItem() const;
  • 3. Node* getNext() const; private: ItemType item; Node* next; }; template Node::Node():next(nullptr){} template Node::Node(const ItemType &anItem):item(anItem), next(nullptr){} template Node::Node(const ItemType &anItem, Node * nextNodePtr):item(anItem), next(nextNodePtr) { } template void Node::setItem(const ItemType &anItem){ item = anItem; } template void Node::setNext(Node * nextNodePtr) { next = nextNodePtr; } template ItemType Node::getItem() const { return item; } template Node* Node::getNext()const{ return next; } #endif /* node_h */ LinkedStack.h #include #ifndef LinkedStack_h #define LinkedStack_h
  • 4. #include "Node.h" #include "StackInterface.h" template class LinkedStack:public StackInterface{ public: LinkedStack(); LinkedStack(const LinkedStack &aStack); //space matter?*********** virtual ~LinkedStack(); bool isEmpty() const; bool push(const ItemType &newItem); bool pop(); ItemType peek() const; private: Node* topPtr; }; template LinkedStack::LinkedStack() : topPtr(nullptr) { } template LinkedStack::LinkedStack(const LinkedStack &aStack) { Node* origChainPtr = aStack->topPtr; if (origChainPtr == nullptr) topPtr = nullptr; else { topPtr = new Node(); topPtr->setItem(origChainPtr->getItem());
  • 5. /**Points to the last node in the new chain */ Node* newChainPtr = topPtr; while (origChainPtr != nullptr) { origChainPtr = origChainPtr->getNext(); ItemType nextItem = origChainPtr->getItem(); Node* newNodePtr = new Node(nextItem); newChainPtr->setNext(newNodePtr); newChainPtr = newChainPtr->getNext(); } newChainPtr->setNext(nullptr); } } /**destructor */ template LinkedStack::~LinkedStack() { //pops until the stack is empty while (!isEmpty()) pop(); } /**isEmpty */
  • 6. template bool LinkedStack::isEmpty() const { return topPtr == nullptr; } /**Push **/ template bool LinkedStack::push(const ItemType &newItem) { Node* newNodePtr = new Node(newItem, topPtr); topPtr = newNodePtr; newNodePtr = nullptr; return true; } template bool LinkedStack::pop() { bool result = false; /* If stack is not empty delete the top item */ if (!isEmpty()) { Node * nodeToDeletePtr = topPtr; topPtr = topPtr->getNext(); //returns deleted node to the system nodeToDeletePtr->setNext(nullptr); delete nodeToDeletePtr; nodeToDeletePtr = nullptr; result = true; } //end if
  • 7. return result; } //end pop template ItemType LinkedStack::peek() const { assert (!isEmpty()); //Enforces precondition return topPtr->getItem(); } #endif /* LinkedStack_h */ Map.h #ifndef Map_h #define Map_h #include #include "LinkedStack.h" #include "City.h" #include #include using namespace std; template class Map { public: void readFlights(); void addToHead(City&anOriginCity, City&aDestinationCity); void verifyRequestedFile(); bool isPath(City&flightCity, City&RequestedCity); private: vector>cityVector; LinkedStack>stackCity; CitynotCity; };
  • 8. template bool Map::isPath(City &flightCity, City &requestedCity) { bool result, done; City*requestedPtr = new City(requestedCity); for (City *tempPtr = flightCity.headPtr; tempPtr != 0; tempPtr = tempPtr->headPtr) { if (tempPtr->destinationCity == requestedPtr->destinationCity) { done = true; return done; } } done = false; return done; } template void Map::verifyRequestedFile() { fstream requestedRoutes; string originCity, destinationCity; bool doesNotMatch; bool correctPath;
  • 9. requestedRoutes.open("RequestFile.txt", ios::in); char test; if (requestedRoutes.is_open()) { while (!requestedRoutes.eof()) { getline(requestedRoutes, originCity, ','); //switched values, so switch back requestedRoutes.get(test); while (requestedRoutes.peek() == 't') { requestedRoutes.get(test); } getline(requestedRoutes, destinationCity, ' '); doesNotMatch = false; for (int i = 0; i < cityVector.size(); i++) { if (cityVector[i].getOriginCity() == originCity) { doesNotMatch = true; notCity.setOriginCity(originCity); notCity.setDestinationCity(destinationCity); correctPath = isPath(cityVector[i], notCity); if (correctPath)
  • 10. cout << "HPair serves from " << originCity << " to " << destinationCity << endl; else cout << "HPair does NOT serve from " << originCity << " to " << destinationCity << endl; } } if (!doesNotMatch) cout << "HPair does not serve " << originCity << endl; } } } template void Map::addToHead(City &anOriginCity, City &aDestinationCity) { City* newOne = new City(aDestinationCity); City* newSecond = new City(anOriginCity); if (anOriginCity.headPtr == 0) { anOriginCity.headPtr = newOne; } else { newOne->headPtr = anOriginCity.headPtr; anOriginCity.headPtr = newOne; }
  • 11. } template void Map::readFlights() { fstream readCities, readFlights; City aCity; string originCity, destinationCity; char test; readCities.open("CityFile.txt", ios::in); if (readCities.is_open()) while (!readCities.eof()) while (getline(readCities, originCity)) { aCity.setOriginCity(originCity); cityVector.push_back(aCity); } for (int i = 0; i < cityVector.size(); i++) readCities.close(); readFlights.open("FlightFile.txt", ios::in); if (readFlights.is_open()) { while (!readFlights.eof()) {
  • 12. getline(readFlights, originCity, ','); readFlights.get(test); while (readFlights.peek() == 't') { readFlights.get(test); } getline(readFlights, destinationCity, ' '); for (int i = 0; i < cityVector.size(); i++) { if (cityVector[i].getOriginCity() == originCity) { notCity.setOriginCity(originCity); notCity.setDestinationCity(destinationCity); addToHead(cityVector[i], notCity); stackCity.push(notCity); } } } } readFlights.close(); } #endif /* Map_h */ City.h #ifndef City_h
  • 13. #define City_h #include #include using namespace std; template class City { public: string originCity; string destinationCity; City *headPtr; City(); City(string origin, string destination); City(const City &aCity); void setOriginCity(string aCityOrigin); void setDestinationCity(string aCityDestination); string getOriginCity(); string getDestinationCity(); void displayOriginCity(); }; template City::City() { originCity = " "; destinationCity = " "; headPtr = 0; } template City::City(string origin, string destination) { originCity = origin; destinationCity = destination; } template City::City(const City &aCity) {
  • 14. this->originCity = aCity.originCity; this->destinationCity = aCity.destinationCity; this->headPtr = aCity.headPtr; } template void City::setOriginCity(string aCityOrigin) { this->originCity = aCityOrigin; } template void City::setDestinationCity(string aCityDestination) { this->destinationCity = aCityDestination; } template void City::displayOriginCity() { cout << this->originCity << endl; } template string City::getOriginCity() { return (this->originCity); } template string City::getDestinationCity() { return(this->destinationCity); } #endif /* City_h */ requestFile.txt Los Angeles, Houston Glendale, Houston Dallas, Austin Cleveland, Chicago Indianapolis, San Francisco
  • 15. San Francisco, Washington Boston, Columbia Miami, Denver flightFile.txt Atlanta, Chicago Boise, Chicago Boston, Chicago Chicago, Atlanta Chicago, Boise Chicago, Boston Chicago, Houston Cleveland, Houston Columbia, Houston Dallas, Houston Denton, Houston Denver, Houston Houston, Glendale Houston, Cleveland Houston, Columbia Houston, Dallas Houston, Denton Houston, Denver Houston, Chicago Indianapolis, Los Angeles Los Angeles, Indianapolis Miami, Los Angeles Miami, Atlanta Atlanta, Miami Los Angeles, Miami San Francisco, Los Angeles Los Angeles, San Francisco Tampa, Los Angeles Los Angeles, Tampa Washington, Los Angeles Los Angeles, Washington cityFile.txt
  • 16. Atlanta Austin Boise Boston Buffalo Chicago Cincinnati Cleveland Columbia Dallas Denton Denver Detroit Everett Glendale Honolulu Houston Indianapolis Irvine Los Angeles Miami Nashville Oakland Reno Salt Lake City San Francisco Tampa Washington Solution class GraphFindAllPaths implements Iterable { /* A map from nodes in the graph to sets of outgoing edges. Each * set of edges is represented by a map from edges to doubles. */ private final Map> graph = new HashMap>(); /** * Adds a new node to the graph. If the node already exists then its a * no-op. * * @param node Adds to a graph. If node is null then this is a no-op. * @return true if node is added, false otherwise. */ public boolean addNode(T node) { if (node == null) { throw new
  • 17. NullPointerException("The input node cannot be null."); } if (graph.containsKey(node)) return false; graph.put(node, new HashMap()); return true; } /** * Given the source and destination node it would add an arc from source * to destination node. If an arc already exists then the value would be * updated the new value. * * @param source the source node. * @param destination the destination node. * @param length if length if * @throws NullPointerException if source or destination is null. * @throws NoSuchElementException if either source of destination does not exists. */ public void addEdge (T source, T destination, double length) { if (source == null || destination == null) { throw new NullPointerException("Source and Destination, both should be non-null."); } if (!graph.containsKey(source) || !graph.containsKey(destination)) { throw new NoSuchElementException("Source and Destination, both should be part of graph"); } /* A node would always be added so no point returning true or false */ graph.get(source).put(destination, length); } /** * Removes an edge from the graph. * * @param source If the source node. * @param destination If the destination node. * @throws NullPointerException if either source or destination specified is null * @throws NoSuchElementException if graph does not contain either source or destination */ public void removeEdge (T source, T destination) { if (source == null || destination == null) { throw new NullPointerException("Source and Destination, both should be non- null."); } if (!graph.containsKey(source) || !graph.containsKey(destination)) { throw new NoSuchElementException("Source and Destination, both should be part of graph"); } graph.get(source).remove(destination); } /** * Given a node, returns the edges going outward that node, * as an immutable map. * * @param node The node whose edges should be queried. * @return An immutable view of the edges leaving that node. * @throws NullPointerException If input node is null. * @throws NoSuchElementException If node is not in graph. */ public Map edgesFrom(T node) { if (node == null) { throw new NullPointerException("The node should not be null."); } Map edges = graph.get(node); if (edges == null) { throw new NoSuchElementException("Source node does not exist."); } return Collections.unmodifiableMap(edges); } /** * Returns the iterator that travels the nodes of a graph. * * @return an iterator that travels the nodes of a graph. */ @Override public Iterator iterator() { return graph.keySet().iterator(); } } /** * Given a connected directed graph, find all paths between any two input points. */ public class FindAllPaths { private final GraphFindAllPaths graph; /** * Takes in a graph. This graph should not be changed by the client */ public FindAllPaths(GraphFindAllPaths graph) { if (graph == null) { throw new NullPointerException("The input graph cannot be null."); }
  • 18. this.graph = graph; } private void validate (T source, T destination) { if (source == null) { throw new NullPointerException("The source: " + source + " cannot be null."); } if (destination == null) { throw new NullPointerException("The destination: " + destination + " cannot be null."); } if (source.equals(destination)) { throw new IllegalArgumentException("The source and destination: " + source + " cannot be the same."); } } /** * Returns the list of paths, where path itself is a list of nodes. * * @param source the source node * @param destination the destination node * @return List of all paths */ public List> getAllPaths(T source, T destination) { validate(source, destination); List> paths = new ArrayList>(); recursive(source, destination, paths, new LinkedHashSet()); return paths; } // so far this dude ignore's cycles. private void recursive (T current, T destination, List> paths, LinkedHashSet path) { path.add(current); if (current == destination) { paths.add(new ArrayList(path)); path.remove(current); return; } final Set edges = graph.edgesFrom(current).keySet(); for (T t : edges) { if (!path.contains(t)) { recursive (t, destination, paths, path); } } path.remove(current); } public static void main(String[] args) { GraphFindAllPaths graphFindAllPaths = new GraphFindAllPaths(); graphFindAllPaths.addNode("A"); graphFindAllPaths.addNode("B"); graphFindAllPaths.addNode("C"); graphFindAllPaths.addNode("D"); graphFindAllPaths.addEdge("A", "B", 10); graphFindAllPaths.addEdge("A", "C", 10); graphFindAllPaths.addEdge("B", "D", 10); graphFindAllPaths.addEdge("C", "D", 10); graphFindAllPaths.addEdge("B", "C", 10); graphFindAllPaths.addEdge("C", "B", 10); FindAllPaths findAllPaths = new FindAllPaths(graphFindAllPaths); List> paths = new ArrayList>(); // ABD List path1 = new ArrayList(); path1.add("A"); path1.add("B"); path1.add("D"); // ABCD List path2 = new ArrayList(); path2.add("A"); path2.add("B"); path2.add("C"); path2.add("D"); //ACD List path3 = new ArrayList(); path3.add("A"); path3.add("C"); path3.add("D"); //ABCD List path4 = new ArrayList(); path4.add("A"); path4.add("C"); path4.add("B"); path4.add("D"); paths.add(path1); paths.add(path2); paths.add(path3); paths.add(path4); findAllPaths.getAllPaths("A", "D"); assertEquals(paths, findAllPaths.getAllPaths("A", "D")); } }