1. Specification
For this assignment, write a static class named ShortestRoute to find the shortest route between San Francisco to New York City. (What makes it "static" is that all its members will be static.)
The class will include two static recursive functions -- the first is simple, and just finds a valid route through the network, without regards to shortest distance. The second finds the shortest route. Both are explained below.
2. Create A Network
Create a constant array of Legs with at least 40 Leg objects. The Leg array you made for the previous Routes versions will probably have to be modified because of the requirements below.
class Leg {
const char* const start;
const char* const end;
const double dist;
friend class Route;
friend class ShortestRoute;
public:
Leg(const char* s, const char* e, double d) :
start(s), end(e), dist(d) {}
double getDistance() const {
return dist;
}
void output(ostream& out) {
out << "Leg: ";
for (int i = 0; i * sizeof('a')
< sizeof(start) / sizeof('a'); i++) {
out <<
start[i];
}
out << " TO ";
for (int i = 0; i * sizeof('a')
< sizeof(start) / sizeof('a'); i++) {
out <<
end[i];
}
out << ", " << dist
<< " miles" << endl;
}
Leg& operator=(const Leg& copyThis) {
Leg& host = *this; // a
reference to the host object
if (this != ©This) {
const_cast(host.start) = copyThis.start;
const_cast(host.end) = copyThis.end;
const_cast(host.dist) = copyThis.dist;
}
return host; //returns a
"self-reference"
}
};
Store the Leg array as a static data member of the ShortestRoute class. The Legs must represent a network of interconnecting cities, between San Francisco and New York City. Use a map of the United States to get the names of intermediate cities of your choice, and the distance between them. Distances do not have to be exact, but they do have to be reasonably close, so that the results generated by your program can be verified.
Every city should have more than one way in (from the west) and more than one way out (to the east), with these exceptions:
3. Find Any Route
class Route {
vector<const Leg*> legs;
const double dist;
friend class ShortestRoute;
public:
Route(const Leg& leg):
dist(leg.dist){
legs =
{&leg};
}
Route(const Route& route, const
Leg& leg): dist(route.legs.back()->end == leg.start ?
route.dist + leg.dist : 0) {
legs =
{route.legs};
if
(legs.back()->end != leg.start) {
throw "End and Start city don't match!";
}
else {
legs.push_back(&leg);
}
}
double getDistance() const{
return
dist;
}
void output(ostream& out)
{
//cout <<
"SIZE " << legs.size()<< endl;
out <<
"Routes: ";
for (unsigned
int i = 0; i < legs.size(); i++) {
out << legs[i]->start << " to
";
}
out <<
legs[legs.size()-1]->end << ", " << dist << "
miles" << endl;
}
Route& operator=(const
Route& copyThis) {
Route& host
= *this; // a reference to the host object
if (this !=
©This) {
host.legs = copyThis.legs;
const_cast<double&>(host.dist) =
copyThis.dist;
}
return host;
//returns a "self-reference"
}
};
Write the recursive function, static const Route anyRoute(const char* const from, const char* const to ), to create and return a Route object that consists of Legs connecting two cities. The solution is explained at the bottom of this writeup, and will be discussed in lecture. Write the main program with a code block like the following:
const Route route1 = ShortestRoute::anyRoute("San Francisco", "New York City");
route1.outputRoute(cout);
The function should throw an exception if no route can be found from the "from" city to the "to" city. If your function returns the superhighway as the solution, you did not put that Leg at the end of your database, as specified.
The function should not produce output -- no cout's! It should return a Route object, period. Same for the 2nd function, described below.
4. Find The Shortest Route
Write the recursive function, static const Route shortestRoute(const char* const from, const char* const to) , to create and return a Route object that consists of legs connecting two cities, such that the legs represent the shortest of all possible routes. Add to main with a statement like the following:
const Route route2 = ShortestRoute::shortestRoute("San Francisco", "New York City");
route2.outputRoute(cout);
The function should use STL techniques to compare and determine the shortest of among possible routes from city "A" to city "B". If no possible route exists, throw an exception. If your function returns the superhighway as the solution, you didn't do this right.
5. Notes
6. About Recursive Solutions
For anyRoute, look through the database of Legs until you find a match between a database's Leg's ending city and the parameter ending city. Once found, see if the database's Leg's beginning city matches the parameter beginning city. Remember -- these are C strings!
If both the start and end match, return a Route object constructed using the 1-parameter Route constructor with the found database Leg as its parameter.
Otherwise just the ending cities match. So create any Route from the parameter beginning city to the found database Leg's beginning city, and return a Route object constructed using the 2-parameter Route constructor with the created "any Route" and the found database Leg as its parameter. How to "create any route"? There's a function for that now, right?...
ShortestRoute::anyRoute returns the first Route it can find. ShortestRoute::shortestRoute is a bit more discriminating. The only difference between the two is instead of returning Routes as anyRoute does, shortestRoute should save the Route to a set and keep looking through the database for more matches with the parameter ending city. When the loop ends, the lead position in the set is the shortest route! Of course, if the set is empty after the loop completes, throw and exception and check your network because something's wrong!
7. Submit Routes.3.cpp
The output should have two routes -- the first generated by "any route" and the second by "shortest route". The first should be longer than the second, if this works right. In the unlikely event that your "any route" just happens to match the "shortest route", scramble your Leg array until that no longer happens. Note that scrambling should affect "any route" but not "shortest route" -- the shortest should be the shortest no matter how the Legs are stored in the array.
Please let me know if you have any doubts or you want me to modify
the answer. And if you find this answer useful then don't forget to
rate my answer as thumps up. Thank you! :)
#include <iostream>
#include <vector>
#include <string>
#include <set>
using namespace std;
#include <cstring>
class Leg {
private:
const char* const startingCity;
const char* const endingCity;
const double distance;
public:
Leg(const char* const, const char* const, const double);
double getDistance() const { return distance;}
void output(ostream&) const;
Leg& operator = (const Leg&);
friend class Route;
friend class ShortestRoute;
};
class Route {
private:
vector<const Leg*> legs;
const double totalDistance;
public:
Route(const Leg&);
Route(const Route&, const Leg&);
double getTotalDist() const {return totalDistance;}
void output(ostream& out) const;
Route& operator = (const Route&);
friend class ShortestRoute;
};
class ShortestRoute {
private:
static const Leg legs[];
public:
static Route anyRoute(const char* const, const char* const);
static Route shortestRoute(const char* const, const char*
const);
};
const Leg ShortestRoute::legs[] = {
Leg("San Francisco", "Sacramento", 87.9), Leg("Sacramento", "Reno",
132),
Leg("Sacramento", "Bakersfield", 286), Leg("Portland",
"Sacramento", 581),
Leg("Reno", "Winnemucca", 166), Leg("Reno", "Salt Lake City",
518),
Leg("Portland", "Reno", 533), Leg("Winnemucca", "Elko", 124),
Leg("Bakersfield", "Winnemucca", 560), Leg("Winnemucca", "Battle
Mountain", 53.5),
Leg("San Francisco", "Bakersfield", 283), Leg("San Francisco",
"Eureka", 271),
Leg("Eureka", "Portland", 409), Leg("San Francisco", "Battle
Mountain", 436),
Leg("Battle Mountain", "Salt Lake City", 300), Leg("Battle
Mountain", "Elko", 70.5),
Leg("Bakersfield", "West Wendover", 647), Leg("West Wendover",
"Albuquerque", 719),
Leg("Elko", "West Wendover", 107), Leg("West Wendover", "Salt Lake
City", 123),
Leg("Rock Spring", "Albuquerque", 653), Leg("Spokane", "Rock
Spring", 758),
Leg("Salt Lake City", "Rock Spring", 187), Leg("Omaha", "New York",
1246),
Leg("Rock Spring", "Cheyenne", 256), Leg("Cheyenne", "Omaha",
494),
Leg("Chicago", "Cincinnati", 299), Leg("Kansas City", "Chicago",
510),
Leg("Omaha", "Chicago", 472), Leg("Chicago", "New York",
790),
Leg("Los Angeles", "Las Vegas", 270), Leg("Bakersfield", "Los
Angeles", 113),
Leg("Phoenix", "Albuquerque", 422), Leg("San Francisco", "Los
Angeles", 383),
Leg("Los Angeles", "Phoenix", 373), Leg("Las Cruces", "Oklahoma
City", 672),
Leg("Las Vegas", "Las Cruces", 685), Leg("Phoenix", "Las Cruces",
388),
Leg("Las Cruces", "Austin", 622), Leg("Austin", "Jacksonville",
1034),
Leg("Jacksonville", "Richmond", 598), Leg("Kansas City",
"Jacksonville", 1144),
Leg("Jacksonville", "New York", 930), Leg("Seattle", "Spokane",
279),
Leg("Richmond", "New York", 333), Leg("San Francisco", "Seattle",
808),
Leg("Seattle", "Great Falls", 642), Leg("Minneapolis", "Chicago",
408),
Leg("Great Falls", "Minneapolis", 967), Leg("Cincinnati",
"Richmond", 514),
Leg("Minneapolis", "Cincinnati", 704), Leg("Cincinnati", "New
York", 639),
Leg("Great Falls", "Cheyenne", 670), Leg("Cheyenne", "Minneapolis",
809),
Leg("Austin", "Omaha", 842), Leg("Salt Lake City", "Kansas City",
1073),
Leg("Bakersfield", "Las Vegas", 286), Leg("Las Vegas", "Phoenix",
298),
Leg("San Francisco", "Portland", 635), Leg("Portland", "Seattle",
173),
Leg("Portland", "Spokane", 351), Leg("Spokane", "Great Falls",
365),
Leg("Portland", "Elko", 627), Leg("Elko", "Cheyenne", 667),
Leg("Las Vegas", "Albuquerque", 574), Leg("Albuquerque", "Austin",
695),
Leg("Albuquerque", "Kansas City", 790), Leg("Oklahoma City",
"Kansas City", 353),
Leg("Oklahoma City", "Nashville", 678), Leg("Salt Lake City",
"Oklahoma City", 1188),
Leg("Austin", "Nashville", 859), Leg("Nashville", "Cincinnati",
272),
Leg("Denver", " Kansas City", 605), Leg("Great Falls", "Denver",
770),
Leg("Nashville", "Richmond", 614), Leg("Las Vegas", "Denver",
748),
Leg("Denver", " Omaha", 538), Leg("San Francisco", "New York",
21000)
};
ostream& roundingOne(ostream&);
bool operator < (const Route&, const Route&);
int main() {
Route greedyRoute = ShortestRoute::anyRoute("San Francisco",
"New York");
Route bestRoute = ShortestRoute::shortestRoute("San Francisco",
"New York");
// Print the shortest route
cout << "------- Shortest Route --------" <<
endl;
bestRoute.output(cout);
// Print any route
cout << "------- Any Route
--------" << endl;
greedyRoute.output(cout);
return 0;
}
Route ShortestRoute::anyRoute(const char* const from, const char*
const to) {
const int legSize = sizeof(legs) / sizeof(*legs);
const Leg *legTo = NULL;
try {
for (int i = 0; i < legSize; i++) {
bool matchDestination = !strcmp(to,
legs[i].endingCity);
bool matchDeparting = !strcmp(from,
legs[i].startingCity);
if (matchDestination &&
matchDeparting) return Route(legs[i]);
if (matchDestination) {
legTo =
&legs[i];
break;
}
}
if (!legTo) throw "No matching arriving city
found";
} catch(const char* err) {
cout << err << endl;
}
return Route(anyRoute(from, legTo->startingCity), *legTo);
}
Route ShortestRoute::shortestRoute(const char* const from, const
char* const to) {
const int legSize = sizeof(legs) / sizeof(*legs);
set<Route> routes;
try {
for (int i = 0; i < legSize; i++) {
bool matchDestination = !strcmp(to,
legs[i].endingCity);
bool matchDeparting = !strcmp(from,
legs[i].startingCity);
if (!strcmp(legs[i].startingCity,
"San Francisco") &&
!strcmp(legs[i].endingCity, "New York")) continue;
if (matchDestination &&
matchDeparting) return Route(legs[i]);
if (matchDestination) {
try {
const Route
candidate(shortestRoute(from, legs[i].startingCity),
legs[i]);
routes.insert(candidate);
} catch(const char* err)
{
continue;
}
}
}
if (routes.empty()) throw "Something went
wrong. Check your legs";
} catch(const char* err) {
cout << err << endl;
}
return *routes.begin();
}
Leg::Leg (const char* const cityA, const char* const cityB,
const double distBtw)
: startingCity(cityA), endingCity(cityB), distance(distBtw)
{
}
void Leg::output(ostream& out) const {
out << "Leg: " << startingCity << " to " <<
endingCity
<< ", " << roundingOne <<
distance << " miles." << endl;
}
ostream& roundingOne(ostream& out) {
out.setf(ios::fixed);
out.precision(1);
return out;
}
Leg& Leg::operator = (const Leg& right) {
Leg &left = *this;
if (this == &right) {
return left;
}
const_cast<const char*&>(left.startingCity) =
right.startingCity;
const_cast<const char*&>(left.endingCity) =
right.endingCity;
const_cast<double&>(left.distance) = right.distance;
return left;
}
Route::Route(const Leg& leg)
: totalDistance(leg.distance)
{
legs.push_back(&leg);
}
Route::Route(const Route& route, const Leg& leg)
: legs(route.legs), totalDistance(0.0)
{
try {
const Leg* lastLeg = legs.back();
if (strcmp(lastLeg->endingCity,
leg.startingCity) != 0)
throw "Cities don't match!";
legs.push_back(&leg);
for (unsigned int i = 0; i < legs.size();
i++) {
const_cast<double&>(totalDistance) +=
legs[i]->getDistance();
}
}
catch (const char* err) {
cout << err << endl;
}
}
void Route::output(ostream& out) const {
const Leg* lastLeg = legs.back();
out << "Route: ";
for( unsigned int i = 0; i < legs.size(); i++)
out << legs[i]->startingCity << "
to ";
out << lastLeg->endingCity << ", " <<
roundingOne
<< totalDistance << endl;
}
Route& Route::operator = (const Route& right) {
Route &left = *this;
if (this == &right) {
return left;
}
left.legs = right.legs;
const_cast<double&>(left.totalDistance) =
right.totalDistance;
return left;
}
bool operator < (const Route& left, const Route&
right) {
return left.getTotalDist() < right.getTotalDist();
}

1. Specification For this assignment, write a static class named ShortestRoute to find the shortest route...
Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver { public static String solve(char[][] grid) { // TODO /* * 1. Construct a graph using grid * 2. Use BFS to find shortest path from start to finish * 3. Return the sequence of moves to get from start to finish */ // Hardcoded solution to toyTest return...
Assignment Overview In Part 1 of this assignment, you will write a main program and several classes to create and print a small database of baseball player data. The assignment has been split into two parts to encourage you to code your program in an incremental fashion, a technique that will be increasingly important as the semester goes on. Purpose This assignment reviews object-oriented programming concepts such as classes, methods, constructors, accessor methods, and access modifiers. It makes use of...
Help C++ Write a string class. To avoid conflicts with other similarly named classes, we will call our version MyString. This object is designed to make working with sequences of characters a little more convenient and less error-prone than handling raw c-strings, (although it will be implemented as a c-string behind the scenes). The MyString class will handle constructing strings, reading/printing, and accessing characters. In addition, the MyString object will have the ability to make a full deep-copy of itself...
Having a rough time getting started with the constructors and the display function of this class, any advice/assitance is appreciated! Task You will write a class called Grid, and test it with a couple of programs. A Grid object will be made up of a grid of positions, numbered with rows and columns. Row and column numbering start at 0, at the top left corner of the grid. A grid object also has a "mover", which can move around to...
CS0007
Good day, I am in an entry-level Java class and need assistance
completing an assignment. Below is the assignment criteria and the
source code from the previous assignment to build
from. Any help would be appreciated, thank you in
advance.
Source Code from the previous assignment to build from shown
below:
Here we go! Let's start with me giving you some startup code: import java.io.*; import java.util.*; public class Project1 { // Random number generator. We will be using this...
Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all others intact and follow similar guidelines. The methods that need to be changed are in the code below. - Rewrite the indexOf() method. Remove the existing recursive implementation of the method, and replace it with one that uses iteration instead. - Rewrite the isPrefix() method so that it uses iteration. Remove the existing recursive implementation of the method, and replace it with one that...
Interfaces 1. What is inside an interface definition? What does a class do to an interface and what keyword is involved? How does a class do this to an interface (what should we find in the class)? Can an interface have a generic parameter? How do you instantiate an interface as an object? What methods can’t you use on an interface type? Abstract Data Types 2. What does an ADT define? Does an ADT specify programming language and/or data structures...
Task The task for this assignment is to have the following user-defined data type: struct rgb { unsigned char red; unsigned char green; unsigned char blue; }; be able to be: read in from a stream (e.g., std::cin), i.e., write: std::istream& operator >>(std::istream& is, rgb& colour); (see below) written out to a stream (e.g., std::cout), i.e., write: std::ostream& operator <<(std::ostream& os, rgb const& colour); (see below) stored in a container, e.g., std::vector<rgb>, std::array<rgb,16>; (see below) processed via algorithms (and other...
For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...
== Programming Assignment == For this assignment you will write a program that controls a set of rovers and sends them commands to navigate on the Martian surface where they take samples. Each rover performs several missions and each mission follows the same sequence: deploy, perform one or more moves and scans, then return to base and report the results. While on a mission each rover needs to remember the scan results, in the same order as they were taken,...