I got this source code from our course material but I can't get it to work. The program is a flight simulator. This link might be useful to understand the bigger picture. Starting on page 67. http://brahms.emu.edu.tr/rza/tr3.pdf
These are the errors that Visual Studio gives to me.
Error E0413 no suitable conversion function from "const Plane" to "const Queue_entry" exists. Runaway.cpp lines 32 & 57
Error E0413 no suitable conversion function from "Extended_queue" to "Runway_activity" exists. Runaway.cpp lines 85 & 93
Error E0434 a reference of type "Queue_entry &" (not const-qualified) cannot be initialized with a value of type "Plane". Runaway.cpp line 96.
Error C2664 'Error_code Queue::append(const Queue_entry &)': cannot convert argument 1 from 'const Plane' to 'const Queue_entry &'. Runaway.cpp lines 32 & 57
Error C2664 'Error_code Queue::retrieve(Queue_entry &) const': cannot convert argument 1 from 'Plane' to 'Queue_entry &'. Runaway.cpp lines 85 & 93
Error C2440 '=': cannot convert from 'Extended_queue' to 'Runway_activity'. Runaway.cpp line 96.
Runaway.h
#include "Utility.h"
#include "Extended_queue.h"
#include "Plane.h"
enum Runway_activity { idle, land, takeoff };
class Runway {
public:
Runway(int limit);
Error_code can_land(const Plane& current);
Error_code can_depart(const Plane& current);
Runway_activity activity(int time, Plane& moving);
void shut_down(int time) const;
private:
Extended_queue landing;
Extended_queue takeoff;
int queue_limit;
int num_land_requests; // number of planes asking to land
int num_takeoff_requests; // number of planes asking to take off
int num_landings; // number of planes that have landed
int num_takeoffs; // number of planes that have taken off
int num_land_accepted; // number of planes queued to land
int num_takeoff_accepted; // number of planes queued to take off
int num_land_refused; // number of landing planes refused
int num_takeoff_refused; // number of departing planes refused
int land_wait; // total time of planes waiting to land
int takeoff_wait; // total time of planes waiting to take off
int idle_time; // total time runway is idle
};
Runaway.cpp
#include "Runway.h"
#include <iostream>
using namespace std;
Runway::Runway(int limit)
/*
Post: The Runway data members are initialized to record no
prior Runway use and to record the limit on queue sizes.
*/
{
queue_limit = limit;
num_land_requests = num_takeoff_requests = 0;
num_landings = num_takeoffs = 0;
num_land_refused = num_takeoff_refused = 0;
num_land_accepted = num_takeoff_accepted = 0;
land_wait = takeoff_wait = idle_time = 0;
}
Error_code Runway::can_land(const Plane& current)
/*
Post: If possible, the Plane current is added to the
landing Queue; otherwise, an Error_code of overflow is
returned. The Runway statistics are updated.
Uses: class Extended_queue.
*/
{
Error_code result;
if (landing.size() < queue_limit)
result = landing.append(current);
else
result = fail;
num_land_requests++;
if (result != success)
num_land_refused++;
else
num_land_accepted++;
return result;
}
Error_code Runway::can_depart(const Plane& current)
/*
Post: If possible, the Plane current is added to the
takeoff Queue; otherwise, an Error_code of overflow is
returned. The Runway statistics are updated.
Uses: class Extended_queue.
*/
{
Error_code result;
if (takeoff.size() < queue_limit)
result = takeoff.append(current);
else
result = fail;
num_takeoff_requests++;
if (result != success)
num_takeoff_refused++;
else
num_takeoff_accepted++;
return result;
}
Runway_activity Runway::activity(int time, Plane& moving)
/*
Post: If the landing Queue has entries, its front
Plane is copied to the parameter moving
and a result land is returned. Otherwise,
if the takeoff Queue has entries, its front
Plane is copied to the parameter moving
and a result takeoff is returned. Otherwise,
idle is returned. Runway statistics are updated.
Uses: class Extended_queue.
*/
{
Runway_activity in_progress;
if (!landing.empty()) {
landing.retrieve(moving);
land_wait += time - moving.started();
num_landings++;
in_progress = land;
landing.serve();
}
else if (!takeoff.empty()) {
takeoff.retrieve(moving);
takeoff_wait += time - moving.started();
num_takeoffs++;
in_progress = takeoff;
takeoff.serve();
}
else {
idle_time++;
in_progress = idle;
}
return in_progress;
}
void Runway::shut_down(int time) const
/*
Post: Runway usage statistics are summarized and printed.
*/
{
cout << "Simulation has concluded after " << time << " time units." << endl
<< "Total number of planes processed "
<< (num_land_requests + num_takeoff_requests) << endl
<< "Total number of planes asking to land "
<< num_land_requests << endl
<< "Total number of planes asking to take off "
<< num_takeoff_requests << endl
<< "Total number of planes accepted for landing "
<< num_land_accepted << endl
<< "Total number of planes accepted for takeoff "
<< num_takeoff_accepted << endl
<< "Total number of planes refused for landing "
<< num_land_refused << endl
<< "Total number of planes refused for takeoff "
<< num_takeoff_refused << endl
<< "Total number of planes that landed "
<< num_landings << endl
<< "Total number of planes that took off "
<< num_takeoffs << endl
<< "Total number of planes left in landing queue "
<< landing.size() << endl
<< "Total number of planes left in takeoff queue "
<< takeoff.size() << endl;
cout << "Percentage of time runway idle "
<< 100.0 * ((float)idle_time) / ((float)time) << "%" << endl;
cout << "Average wait in landing queue "
<< ((float)land_wait) / ((float)num_landings) << " time units";
cout << endl << "Average wait in takeoff queue "
<< ((float)takeoff_wait) / ((float)num_takeoffs)
<< " time units" << endl;
cout << "Average observed rate of planes wanting to land "
<< ((float)num_land_requests) / ((float)time)
<< " per time unit" << endl;
cout << "Average observed rate of planes wanting to take off "
<< ((float)num_takeoff_requests) / ((float)time)
<< " per time unit" << endl;
}
Plane.h
#pragma once
#include "Utility.h"
enum Plane_status { null, arriving, departing };
class Plane {
public:
Plane();
Plane(int flt, int time, Plane_status status);
void refuse() const;
void land(int time) const;
void fly(int time) const;
int started() const;
private:
int flt_num;
int clock_start;
Plane_status state;
};
Plane.cpp
#include "Plane.h"
#include <iostream>
using namespace std;
Plane::Plane(int flt, int time, Plane_status status)
/*
Post: The Plane data members flt_num, clock_start,
and state are set to the values of the parameters flt,
time and status, respectively.
*/
{
flt_num = flt;
clock_start = time;
state = status;
cout << "Plane number " << flt << " ready to ";
if (status == arriving)
cout << "land." << endl;
else
cout << "take off." << endl;
}
Plane::Plane()
/*
Post: The Plane data members flt_num, clock_start,
state are set to illegal default values.
*/
{
flt_num = -1;
clock_start = -1;
state = null;
}
void Plane::refuse() const
/*
Post: Processes a Plane wanting to use Runway, when
the Queue is full.
*/
{
cout << "Plane number " << flt_num;
if (state == arriving)
cout << " directed to another airport" << endl;
else
cout << " told to try to takeoff again later" << endl;
}
void Plane::land(int time) const
/*
Post: Processes a Plane that is landing at the specified time.
*/
{
int wait = time - clock_start;
cout << time << ": Plane number " << flt_num << " landed after "
<< wait << " time unit" << ((wait == 1) ? "" : "s")
<< " in the takeoff queue." << endl;
}
void Plane::fly(int time) const
/*
Post: Process a Plane that is taking off at the specified time.
*/
{
int wait = time - clock_start;
cout << time << ": Plane number " << flt_num << " took off after "
<< wait << " time unit" << ((wait == 1) ? "" : "s")
<< " in the takeoff queue." << endl;
}
int Plane::started() const
/*
Post: Return the time that the Plane entered the airport system.
*/
{
return clock_start;
}
Extended_queue.h
#pragma once
#include "Queue.h"
class Extended_queue : public Queue {
public:
bool full() const;
int size() const;
void clear();
Error_code serve_and_retrieve(Queue_entry& item);
void print();
};
Extended_queue.cpp
#include "Extended_queue.h"
int Extended_queue::size() const
/*
Post: Return the number of entries in the Extended_queue.
*/
{
return count;
}
bool Extended_queue::full() const
{
return maxqueue == this->count;
}
void Extended_queue::clear()
{
this->count = 0;
this->front = 0;
this->rear = maxqueue - 1;
}
Error_code Extended_queue::serve_and_retrieve(Queue_entry& item)
{
if (count <= 0) return underflow;
item = entry[front];
count--;
front = ((front + 1) == maxqueue) ? 0 : (front + 1);
return success;
}
void Extended_queue::print()
{
for (int i = 0, j = front;
i < this->count; i++, j = ((j + 1) == maxqueue) ? 0 : (j + 1))
cout << this->entry[j] << ' ';
cout << endl;
}
Queue.h
#include "Utility.h"
typedef char Queue_entry;
const int maxqueue = 1000; // small value for testing
class Queue {
public:
Queue();
bool empty() const;
Error_code serve();
Error_code append(const Queue_entry& item);
Error_code retrieve(Queue_entry& item) const;
protected:
int count;
int front, rear;
Queue_entry entry[maxqueue];
};
Queue.cpp
#include "Queue.h"
Queue::Queue()
/*
Post: The Queue is initialized to be empty.
*/
{
count = 0;
rear = maxqueue - 1;
front = 0;
}
bool Queue::empty() const
/*
Post: Return true if the Queue is empty, otherwise return false.
*/
{
return count == 0;
}
Error_code Queue::append(const Queue_entry& item)
/*
Post: item is added to the rear of the Queue. If the Queue is full
return an Error_code of overflow and leave the Queue unchanged.
*/
{
if (count >= maxqueue) return overflow;
count++;
rear = ((rear + 1) == maxqueue) ? 0 : (rear + 1);
entry[rear] = item;
return success;
}
Error_code Queue::serve()
/*
Post: The front of the Queue is removed. If the Queue
is empty return an Error_code of underflow.
*/
{
if (count <= 0) return underflow;
count--;
front = ((front + 1) == maxqueue) ? 0 : (front + 1);
return success;
}
Error_code Queue::retrieve(Queue_entry& item) const
/*
Post: The front of the Queue retrieved to the output
parameter item. If the Queue is empty return an Error_code of underflow.
*/
{
if (count <= 0) return underflow;
item = entry[front];
return success;
}
Utility.h
#pragma once
#include <iostream>
using namespace std;
enum Error_code {
success, fail, utility_range_error, underflow, overflow, fatal, not_present,
duplicate_error, entry_inserted, entry_found, internal_error
};
bool user_says_yes();
Utility.cpp
#include "Utility.h"
#include <iostream>
using namespace std;
bool user_says_yes()
{
int c;
bool initial_response = true;
do { // Loop until an appropriate input is received.
if (initial_response)
cout << " (y,n)? " << flush;
else
cout << "Respond with either y or n: " << flush;
do { // Ignore white space.
c = cin.get();
} while (c == '\n' || c == ' ' || c == '\t');
initial_response = false;
} while (c != 'y' && c != 'Y' && c != 'n' && c != 'N');
return (c == 'y' || c == 'Y');
}
Main.cpp
#include "Random.h"
#include "Plane.h"
#include "Runway.h"
#include "Utility.h"
#include <iostream>
using namespace std;
void run_idle(int time)
/*
Post: The specified time is printed with a message that the runway is idle.
*/
{
cout << time << ": Runway is idle." << endl;
}
void initialize(int& end_time, int& queue_limit,
double& arrival_rate, double& departure_rate)
/*
Pre: The user specifies the number of time units in the simulation,
the maximal queue sizes permitted,
and the expected arrival and departure rates for the airport.
Post: The program prints instructions and initializes the parameters
end_time, queue_limit, arrival_rate, and departure_rate to
the specified values.
Uses: utility function user_says_yes
*/
{
cout << "This program simulates an airport with only one runway." << endl
<< "One plane can land or depart in each unit of time." << endl;
cout << "Up to what number of planes can be waiting to land "
<< "or take off at any time? " << flush;
cin >> queue_limit;
cout << "How many units of time will the simulation run?" << flush;
cin >> end_time;
bool acceptable;
do {
cout << "Expected number of arrivals per unit time?" << flush;
cin >> arrival_rate;
cout << "Expected number of departures per unit time?" << flush;
cin >> departure_rate;
if (arrival_rate < 0.0 || departure_rate < 0.0)
cerr << "These rates must be nonnegative." << endl;
else
acceptable = true;
if (acceptable && arrival_rate + departure_rate > 1.0)
cerr << "Safety Warning: This airport will become saturated. " << endl;
} while (!acceptable);
}
int main()
// Airport simulation program
/*
Pre: The user must supply the number of time intervals the simulation is to
run, the expected number of planes arriving, the expected number
of planes departing per time interval, and the
maximum allowed size for runway queues.
Post: The program performs a random simulation of the airport, showing
the status of the runway at each time interval, and prints out a
summary of airport operation at the conclusion.
Uses: Classes Runway, Plane, Random and functions run_idle, initialize.
*/
{
int end_time; // time to run simulation
int queue_limit; // size of Runway queues
int flight_number = 0;
double arrival_rate, departure_rate;
initialize(end_time, queue_limit, arrival_rate, departure_rate);
Random variable;
Runway small_airport(queue_limit);
for (int current_time = 0; current_time < end_time; current_time++) { // loop over time intervals
int number_arrivals = variable.poisson(arrival_rate); // current arrival requests
for (int i = 0; i < number_arrivals; i++) {
Plane current_plane(flight_number++, current_time, arriving);
if (small_airport.can_land(current_plane) != success)
current_plane.refuse();
}
int number_departures = variable.poisson(departure_rate); // current departure requests
for (int j = 0; j < number_departures; j++) {
Plane current_plane(flight_number++, current_time, departing);
if (small_airport.can_depart(current_plane) != success)
current_plane.refuse();
}
Plane moving_plane;
switch (small_airport.activity(current_time, moving_plane)) {
// Let at most one Plane onto the Runway at current_time.
case land:
moving_plane.land(current_time);
break;
case takeoff:
moving_plane.fly(current_time);
break;
case idle:
run_idle(current_time);
}
}
small_airport.shut_down(end_time);
}
I have tried to solve this for two days now so I really need help. Thanks in advance!
You're trying to fix a Plane inside a char sized hole. The compiler is telling you that it doesn't know how to convert a Plane to a Queue_entry which you define to be a char.
If you want it to be able to your Plane should inherit from Queue_entry. You should familiarize yourself with polymorphism, as it seems like that's what you're going for.
But even then it's likely that things won't work out as it does not seem like you have fully considered the memory allocation of your objects. If you want to put objects in a vector they will be allocated by the vector as necessary. This means you cannot have a vector of interfaces, as the object implementing the interface could have any size. What you could do instead is have a vector of unique_ptr<Queue_entry>.
Related
I wrote a queue program based on a checkout simulation taking data from a text file (sim.txt). I got everything to work in my code except for one thing. I want to organize each sim result by numbers.
sim.txt
2000
0.10
5
15
5
20
10000
0.05
5
15
5
18
2000
0.20
5
20
10
10
2000
0.20
1
5
10
25
20000
0.50
1
2
50
10
Here is an example output
Simulation Results #1
// result #1 output is here...
Simulation Results #2
// result #2 output is here...
Simulation Results #3
// result #3 output is here...
Simulation Results #4
// result #4 output is here...
Simulation Results #5
// result #5 output is here...
I tried implementing a for loop to achieve this, but it didn't work as expected. This problem occurs for each simulation result.
Simulation Results #1
Simulation Results #2
Simulation Results #3
Simulation Results #4
Simulation Results #5
// result #1 outputs here...
Here is my code to get a better look what I'm doing
#include <iostream>
#include <cstdlib>
#include <queue>
#include <fstream>
#include <ctime>
using namespace std;
// Input parameters
#define SIMULATION_TIME 0
#define ARRIVAL_RATE 1
#define MIN_SERVICE_TIME 2
#define MAX_SERVICE_TIME 3
#define MAX_LINE_SIZE 4
#define ANGRY_THRESHOLD 5
#define PARAMS_MAX 6
#define FILENAME "sim.txt"
// Or like this:
// const int SIMULATION_TIME = 0;
// Or make 6 variables:
// double SIMULATION_TIME = 0;
// Counters -- indexes into variable 'counters' below
#define CUSTOMERS_SERVICED 0
#define CUSTOMERS_LEAVING 1
#define AVERAGE_WAIT 2
#define AVERAGE_LINE 3
#define ANGRY_CUSTOMERS 4
#define COUNTERS_MAX 5
// Holds the current simulation parameters
double parameters[PARAMS_MAX];
double counters[COUNTERS_MAX];
// This is an example debug macro you can use to print
// things each time through the loop
#define DEBUGGING_ENABLED 1
#ifdef DEBUGGING_ENABLED
#define DEBUG(x) do { \
cerr << __FILE__ << ": " << __LINE__ << ": " << x << endl; \
} while (0)
#else
#define DEBUG(x)
#endif // DEBUGGING_ENABLED
// Return the service interval, between 'min'
// and 'max'.
int randomInt(int min, int max)
{
return (rand() % (max - min) + min);
}
// Returns TRUE if a customer arrived during this minute
bool randomChance(double prob)
{
double rv = rand() / (double(RAND_MAX) + 1);
return (rv < prob);
}
// Read the next simulation from the file. Return
// TRUE if one could be read, FALSE otherwise (eof).
bool readNextSim(fstream &f, double parameters[])
{
for (int i = 0; i < PARAMS_MAX; i++)
{
string tmp;
getline(f, tmp);
if (f.eof())
return false;
// Read in the next parameter
parameters[i] = atof(tmp.c_str());
}
for (int i = 0; i < 5; i++)
cout <<"Simulation Results #" << i + 1 << endl;
cout << "---------------------" << endl;
cout << "\t Overall simulation time: " << "\t" << parameters[SIMULATION_TIME] << endl;
cout << "\t Arrival rate: " << "\t\t\t" << parameters[ARRIVAL_RATE] << endl;
cout << "\t Minimum service time: " << "\t\t" << parameters[MIN_SERVICE_TIME] << endl;
cout << "\t Maximum service time: " << "\t\t" << parameters[MAX_SERVICE_TIME] << endl;
cout << "\t Maximum line size: " << "\t\t" << parameters[MAX_LINE_SIZE] << endl;
cout << "\t Angry threshold: " << "\t\t" << parameters[ANGRY_THRESHOLD] << endl;
return true;
}
int main()
{
fstream f(FILENAME);
// Seed the random number generator here
srand(time(0));
if (!f.good())
{
cout << "Invalid file." << endl;
return -1;
}
while (readNextSim(f, parameters))
{
// Run the next simulation
queue<int> line;
for (int i = 0; i < COUNTERS_MAX; i++)
counters[i] = 0;
// or:
// memset(counters, 0, COUNTERS_MAX * sizeof(double));
//int customersLeavingLineFull = 0;
int simTime = 0;
int currentCustomer = -1;
// Each time through this loop represents 1 minute passing.
// There needs to be code to handle everything that can happen
// in 1 minute:
// - Customer arriving (yes/no?)
// - Is the current customer finished
// - Possibly process the next person in line
// - Calculate simulation statistics along the way
while (simTime++ < parameters[SIMULATION_TIME])
{
// One iteration of the loop represents one
// minute of simulation time.
// Check to see if a customer arrived
// (if so, process, also see if the line is full)
bool arrived = randomChance(parameters[ARRIVAL_RATE]);
if (arrived)
{
// A customer arrived in this minute
if (currentCustomer == -1)
{
// No customer is currently at the cashier
int serviceTime = randomInt(parameters[MIN_SERVICE_TIME],
parameters[MAX_SERVICE_TIME]);
currentCustomer = simTime + serviceTime;
}
else
{
if (line.size() == parameters[MAX_LINE_SIZE])
{
// Count this customer as leaving because the line is too
// full
counters[CUSTOMERS_LEAVING]++;
}
else
{
line.push(simTime);
}
}
}
counters[AVERAGE_LINE] += line.size();
// Check to see if the current customer is done
// at the cashier. Also check if there is no customer
// at the cashier (in which the next customer goes to the
// cashier).
if (simTime == currentCustomer)
{
if (!line.empty())
{
int nextCustomerTimestamp = line.front();
int waitingTime = simTime - nextCustomerTimestamp;
// We need to include this in the average waiting times
if (waitingTime >= parameters[ANGRY_THRESHOLD])
counters[ANGRY_CUSTOMERS]++;
counters[AVERAGE_WAIT] += waitingTime;
// Set currentCustomer to the time when that customer
// will be done. Need to call randomInt().
int serviceTime = randomInt(parameters[MIN_SERVICE_TIME],
parameters[MAX_SERVICE_TIME]);
// This will give us a timestamp of when the current customer will
// be done.
currentCustomer = simTime + serviceTime;
line.pop();
counters[CUSTOMERS_SERVICED]++;
}
else
{
// The line is empty
counters[CUSTOMERS_SERVICED]++;
currentCustomer = -1;
}
}
}
// Print a summary of the simulation:
// counters
counters[AVERAGE_WAIT] /= counters[CUSTOMERS_SERVICED];
counters[AVERAGE_LINE] /= parameters[SIMULATION_TIME];
cout << endl;
cout << "\t Customers serviced: " << "\t\t" << counters[CUSTOMERS_SERVICED] << endl;
cout << "\t Customers leaving: " << "\t\t" << counters[CUSTOMERS_LEAVING] << endl;
cout << "\t Average time spent in line: " << "\t" << counters[AVERAGE_WAIT] << endl;
cout << "\t Average line length: " << "\t\t" << counters[AVERAGE_LINE] << endl;
cout << "\t Angry customers: " << "\t\t" << counters[ANGRY_CUSTOMERS] << endl;
cout << endl;
}
return 0;
}
Any advice on how to achieve the example output above would be appreciated!
Write a program that asks for the names of three runners and the time it took each
of them to finish a race. The program should display who came in first, second, and
third place.
Input Validation: Only accept positive numbers for the times.
My Code
#include <iostream>
#include <string>
using namespace std;
int main()
{
string runner1, runner2, runner3;
int time1, time2, time3;
cout << "Please enter the names of three runners" << endl;
cin >> runner1 >> runner2 >> runner3;
cout << "How many minutes did it take " << runner1 << " to finish the race?" << endl;
cin >> time1;
cout << "How many minutes did it take " << runner2 << " to finish the race?" << endl;
cin >> time2;
cout << "How many minutes did it take " << runner3 << " to finish the race?" << endl;
cin >> time3;
if (time1 < time2 && time1 < time3)
{
cout << runner1 << " is 1st place!" << endl;
if (time2 < time3)
{
cout << runner2 << " is 2nd place!" << endl;
cout << runner3 << " is 3rd place!" << endl;
}
else if (time3 < time2)
{
cout << runner3 << " is 2nd place!" << endl;
cout << runner2 << " is 3rd place!" << endl;
}
}
else if (time2 < time1 && time2 < time3)
{
cout << runner2 << " is 1st place!" << endl;
if (time1 < time3)
{
cout << runner1 << " is 2nd place!" << endl;
cout << runner3 << " is 3rd place!" << endl;
}
else if (time3 < time1)
{
cout << runner3 << " is 2nd place!" << endl;
cout << runner2 << " is 3rd place!" << endl;
}
}
else if (time3 < time2 && time3 < time1)
{
cout << runner3 << " is 1st Place!" << endl;
if (time2 < time1)
{
cout << runner2 << " is 2nd place!" << endl;
cout << runner1 << " is 3rd place!" << endl;
}
else if (time1 < time2)
{
cout << runner1 << " is 2nd place!" << endl;
cout << runner2 << " is 3rd place!" << endl;
}
}
else
{
cout << "Error! Please restart the program and input a positive value" << endl;
}
return 0;
}
Keep the runners ordered in an array by their time, iterate over the runners array and output (name + i + " place")
I think a linked list would be really good, but it might lose to a raw array if the runners don't change place very often or if there aren't many runners.
"Separate the drawing code from the game logic"
Your drawing code is cout calls. Your game logic is determining what place each runner is in. Then you draw based on that state that you calculated.
Your way is the most direct and fastest way to solve the problem of printing out runner places though.
#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
struct Runner {
int time;
int id;
int operator<(Runner runner) {
return time < runner.time;
}
};
char* pickSuffix(int place) {
switch (place) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
int main() {
//make my runners, read in my times, runner 1 first
Runner runners[3];
for (int i = 0; i < 3; i++) {
cout << "Enter runner " << i+1 << "'s time: ";
cin >> runners[i].time;
cout << endl;
runners[i].id = i+1; //setup their id, used like a name
}
//figure out what place each runner came in
//must overload operator< for object to use sort
sort(runners, &runners[2]);
//the position of the runner in the array is the place they came in
//since it is sorted by their times
for (int i = 0; i < 3; i++) {
cout << "Runner #" << runners[i].id << " came in " << i+1 << pickSuffix(i+1) << " place!" << endl;
cout << runners[i].time << endl;
}
system("pause");
return 0;
}
Here is a sample of the code written the way I described. I think for most purposes you wouldn't want to sort the runners in the array though, you would add a member variable place and just store their calculated position.
It looks like you're beginning your journey in c++ programming. Welcome.
I'd seek to break the problem down into its component parts, so that we can end up expressing the intent of the solution in an easy-to-understand form:
int solve(std::istream& is, std::ostream& os) {
Runners runners;
collect_runners(os, is, runners);
sort_by_time(runners);
print_first_3(os, runners);
return 0;
}
Note that I have not tied the solution to any particular input or output stream. That's so I can test it easily later.
Now that we have expressed the intent of the solution cleanly, we fill in the blanks (I have used various 'advanced' techniques that I hope you will find instructive and interesting).
I have used c++11.
Comments inline.
#include <string>
#include <vector>
#include <algorithm>
#include <type_traits>
#include <iostream>
#include <sstream>
/** The concept of coupling a runner's name with the time it took to run the race
*
*/
struct Runner {
std::string name;
int time;
};
/** A collection of runners and their corresponding time.
*
*/
using Runners = std::vector<Runner>;
/** Sort a container with a predicate. Return a reference to the container
*
* #tparam Container
* #tparam Pred
* #param c
* #param pred
* #return
*/
template<class Container, class Pred>
auto sort_container(Container &c, Pred &&pred) -> Container & {
std::sort(std::begin(c), std::end(c), std::forward<Pred>(pred));
return c;
}
/** Sort a Runners array by ascending time
*
* #param vec
* #return
* */
Runners &sort_by_time(Runners &vec) {
auto by_increasing_time = [](Runner const& l, Runner const& r) {
return l.time < r.time;
};
sort_container(vec, by_increasing_time);
return vec;
}
/** Print the first 3 runnes in an array of runners to an ostream
*
* #param os
* #param vec
*/
void print_first_3(std::ostream& os, Runners const &vec) {
static const char *nth[] = {
"first",
"second",
"third"
};
auto limit = std::extent<decltype(nth)>::value;
limit = std::min(limit, vec.size());
for (std::size_t i = 0; i < limit; ++i) {
auto const &runner = vec[i];
os << runner.name << " is in " << nth[i] << " place with a time of " << runner.time << "\n";
}
}
/** Ask a question on the console if the answer is to come from stdin
*
* #param is
* #param q
*/
template<class Target>
void question(std::istream& is, Target& target, std::string const& q)
{
if (std::addressof(is) == static_cast<std::istream*>(std::addressof(std::cin)))
{
std::cout << q << std::endl;
}
is >> target;
}
/** Build a runner using the supplied input and output streams
*
* #param os
* #param is
* #return
*/
Runner collect_runner(std::ostream& os, std::istream& is)
{
Runner runner {};
question(is, runner.name, "runner's name?");
question(is, runner.time, "runner's time?");
return runner;
}
/** Populate a Runners array using input and output streams
*
* #param os
* #param is
* #param runners
* #return
*/
Runners& collect_runners(std::ostream& os, std::istream& is, Runners& runners)
{
int nrunners = 0;
question(is, nrunners, "how many runners?");
while (nrunners-- > 0) {
runners.push_back(collect_runner(os, is));
}
return runners;
}
/** Solve the problem at hand
*
* #param is
* #param os
* #return
*/
int solve(std::istream& is, std::ostream& os) {
Runners runners;
collect_runners(os, is, runners);
sort_by_time(runners);
print_first_3(os, runners);
return 0;
}
/** Solve the problem using either std input/output or test input
*
* #param argc
* #param argv
* #note If argc == 2 and argv[1] == "test" then run solve using test input.
* We do this so that we can test our code without playing around with external files or
* the console each time we want to test it
* #return
*/
int main(int argc, char **argv) {
if (argc == 2 && argv[1] == std::string("test")) {
static const char test_data[] = R"__(
5
bob 40
bill 20
sue 30
peter 25
zool 29
)__";
std::istringstream test_stream{test_data};
return solve(test_stream, std::cout);
} else {
return solve(std::cin, std::cout);
}
}
test on the console with:
$ ./a.out test
expected output:
bill is in first place with a time of 20
peter is in second place with a time of 25
zool is in third place with a time of 29
I may have laughed a little at the complexity of Richard's answer.
He makes excellent points about organizing code, of course.
I end up posting my own review and a "simpler" sample, because I think the most important side of a program is functionality.
In this case,
you need error handling (the user may enter illegal values)
you need to check input (the user may enter more than 3 names, may enter identical names etc)
you need to properly report ranks. If two runners had the same time, you will rank them in "arbitrary" order. You will want to correctly rate them as shared places.
My code
is less tied to 3 runners (only when reading the three names, because that's what the sample required)
exemplifies the use of partial_sort to get just the first 3 positions sorted That is no longer possible since the display function handles collections of unknown size and sharing places implies there maybe more than 3 ranked runners.
Live On Coliru
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
void static inline ignore_rest_of_line() {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
struct Runner {
std::string name;
int time = 0;
bool operator<(Runner const& o) const { return time < o.time; }
};
std::vector<Runner> read_three() {
std::string name1, name2, name3;
auto unique = [&] { return std::set<std::string>{ name1, name2, name3 }.size() == 3; };
std::cout << "Please enter the names of three runners\n";
while (std::cin) {
if (std::cin >> name1 >> name2 >> name3 && unique())
break;
std::cout << "Enter 3 unique names\n";
ignore_rest_of_line();
}
ignore_rest_of_line();
return { { name1, 0 }, { name2, 0 }, { name3, 0 } };
}
void read_time(Runner& runner) {
while (std::cin) {
std::cout << "How many minutes did it take " << runner.name << " to finish the race?\n";
if ((std::cin >> runner.time) && runner.time > 0)
break;
std::cout << "Enter a valid time\n";
std::cin.clear();
ignore_rest_of_line();
}
ignore_rest_of_line();
}
template <typename List>
void display_winners(List runners) {
std::sort(std::begin(runners), std::end(runners));
std::string ranks[] = { "1st", "2nd", "3rd" };
auto prev = runners.begin();
auto rank = std::begin(ranks);
for (auto& runner : runners) {
if (runner.time != prev->time)
++rank;
if (rank == std::end(ranks))
break;
std::cout << runner.name << " is " << *rank << " place\n";
}
}
int main() {
std::cin.exceptions(std::ios::eofbit);
auto runners = read_three();
for (auto& runner : runners) {
read_time(runner);
}
display_winners(runners);
}
The sample run shows
Please enter the names of three runners
a a b
Enter 3 unique names
a b c
How many minutes did it take a to finish the race?
9
How many minutes did it take b to finish the race?
invalid time 7
Enter a valid time
How many minutes did it take b to finish the race?
8
How many minutes did it take c to finish the race?
8
c is 1st place
b is 1st place
a is 2nd place
I'm having problems with my program's output. It keeps spitting out 12345.
Here's the details:
It's split in three files: program8.cpp (the part that runs tests), myRandom.cpp (implementation of the class), and myRandom.h (specification of the class).
myRandom.h:
#ifndef MYRANDOM_H_
#define MYRANDOM_H_
class myRandom
{
public:
myRandom(); //Constructor
~myRandom(); //Destructor
void seed(unsigned long theSeed); //Mutator for current
unsigned long next(); //Mutator or Accessor for current
int randInt(int start, int end); //Scales result to a range
double randNormal(); //Future expansion
private:
unsigned long current; //Current random #
static const unsigned long a = 1103515245; //Multiplier for LGC
static const unsigned long c = 12345; //Increment for LGC
static const unsigned long m = 2147483648; //Modulus for LGC
};
#endif /* MYRANDOM_H_ */
myRandom.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
myRandom::myRandom() //Constructor
{
current = 0;
}
myRandom::~myRandom() //Destructor
{
}
void myRandom::seed(unsigned long theSeed) //Mutator for current
{
if (theSeed < 0 || theSeed > m-1)
{
// ERROR
return;
}
else
current = theSeed;
}
unsigned long myRandom::next() //Mutator or Accessor for current
{
if (current < 0)
{
cout << "Error: cannot set seed to a negative number" << endl;
return 0;
}
else
{
current = (m*current+c)%m; //Formula
return current;
}
}
int myRandom::randInt(int start, int end) //Scales result to a range
{
if (start >= end)
{
cout << "Error: cannot set start greater than or equal to end" << endl;
return 0;
}
else
{
return ((this->next() % (end - start)) + start);
}
}
double myRandom::randNormal() //Future expansion
{
cout << "Warning: randNormal not implemented" << endl;
return 0;
}
program8.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
int main()
{
myRandom theRand;
unsigned long theSeed;
cout << "Verify that the sequence generated by next() is the same on each run" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.next() << endl;
}
cout << "Verify that you can set the seed to 0 and 1" << endl;
theSeed = 0;
cout << theRand.next() << endl;
theSeed = 1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to -1 generates an error" << endl;
theSeed = -1;
cout << theRand.next() << endl;
cout << "Verify that you can set the seed to m-2 and m-1" << endl;
theSeed = 2147483648-2;
cout << theRand.next() << endl;
theSeed = 2147483648-1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to m generates and error" << endl;
theSeed = 2147483648;
cout << theRand.next() << endl;
cout << "Verify that next() produces a sequence predicted by hand/calc for the chosen seed" << endl;
cout << "Please enter a seed: ";
cin >> theSeed;
cout << theRand.next() << endl;
cout << "Verify that using start == end generates and error. Set both to 10." << endl;
theRand.randInt(10,10);
cout << theRand.next() << endl;
cout << "Verify that using start > end generates and error. Set start to 10 and end to 5." << endl;
theRand.randInt(10,5);
cout << theRand.next() << endl;
theRand.seed(theSeed);
cout << "Testing randInt for start=0 end=1,000" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.randInt(0 , 1000) << endl;
}
return 0;
}
I think the problem lies in the next() function, since that's what gets called all those times in program8.cpp cout statements. I could understand getting 12345 once, but it should be updated once that function runs successive times. I apologize if it's a dumb question. Thank you for your time and patience.
Your problem isn't a code specific one - it is Math-related from here:
current = (m*current+c)%m;
This always returns the value of c if c < m, otherwise (or more generally) it returns c % m. Why? From this theorem:
(m*n + a)%m = a
Example:
m = 10
n = 3
a = 7
(10*3 + 7)%10 = 7
See this for more:
http://en.wikipedia.org/wiki/Modulo_operation
I get the following assertion errors after the control passes the return statement:
_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
CrtIsValidHeapPointer(pUserData)
while trying to run this code:
main.cpp
#include <iostream>
#include "Queue.h"
#include "Customer.h"
using namespace std;
int main() {
Queue q1;
Queue q2(3);
Queue q3(5);
for (int i = 0; i < 13; i++)
{
Customer c(i);
bool in = q1.enqueue(c);
if (i <= 9 && !in)
{
cout << "ERROR: default size is smaller than 10!!" << endl;
}
else if (i > 9 && in)
{
cout << "ERROR: default size is bigger than 10!!" << endl;
}
}
q1.print();
cout << "0 1 2 3 4 5 6 7 8 9 ***********" << endl;
for (int i = 0; i < 10; i++)
{
Customer el = q1.dequeue();
if (i != el.getId()){
cout << "Error: dequeue order is not correct!!";
}
}
cout << endl;
Customer underflow = q1.dequeue();
if (underflow.getId() != 0)
{
cout << "ERROR: underflow not taken care of!!" << endl;
}
Customer c1(12, "moni");
if (!q3.enqueue(c1))
{
cout << "ERROR: cannot add element to queue 3!!" << endl;
}
Customer c2(14, "mobi");
if (!q3.enqueue(c2)){
cout << "ERROR: cannot add element to queue 3!!" << endl;
}
Queue q4(q3);
if (q3.dequeue().getId() != 12)
{
cout << "ERROR: cdequeue should return the first element in line (12)!!" << endl;
}
if (!q4.enqueue(21)){
cout << "ERROR: cannot add element to queue 4!!" << endl;
}
if (!q4.enqueue(7)){
cout << "ERROR: cannot add element to queue 4!!" << endl;
}
if (!q4.enqueue(332)){
cout << "ERROR: cannot add element to queue 4!!" << endl;
}
if (q4.enqueue(12)){
cout << "ERROR: add element number 6 to queue with size 5 (q4)!!" << endl;
}
q4.print();
cout << "12 14 21 7 332 ***********" << endl;
q3.print();
cout << "14 ***********" << endl;
q2.print();
cout << "queue is empty! ***********" << endl;
q2 = q3;
q2.print();
cout << "14 ***********" << endl;
if (!q2.enqueue(17)){
cout << "ERROR: cannot add element to queue 2!!" << endl;
}
if (!q2.enqueue(18)){
cout << "ERROR: cannot add element to queue 2!!" << endl;
}
if (!q2.enqueue(3521)){
cout << "ERROR: cannot add element to queue 2!!" << endl;
}
q2.print();
cout << "14 17 18 3521 ***********" << endl;
q3.print();
cout << "14 ***********" << endl;
return 0;
}
Queue.h
#ifndef _QUEUE_H_
#define _QUEUE_H_
#include <stdio.h>
#include "Customer.h"
class Queue {
private:
Customer *elements; // Holds the elements of this queue.
int mSize; // Size of the queue
int mTop; // Index of the last element in the queue.
public:
static const int DEFAULT_SIZE = 10;
// Default constructor
Queue() : mSize(DEFAULT_SIZE), mTop(-1) {
elements = new Customer[DEFAULT_SIZE];
}
// Copy constructor
Queue(const Queue &q) : mSize(q.mSize), mTop(q.mTop) {
elements = new Customer[mSize];
for(int i = 0; i <= mTop; i++){
elements[i] = q.elements[i];
}
}
// Initialize a new Queue with the specified size.
explicit Queue(int size) : mSize(size), mTop(-1) {
elements = new Customer[size];
}
// Add the given Customer to the end of the queue.
// Returns true if the Customer was added, false if the Queue is full.
bool enqueue(Customer);
// Remove the first Customer from the Queue.
// Returns the Customer that was removed.
Customer dequeue();
// Print the IDs of the Customers in this Queue in the order
// in which they will be attended.
void print() const;
~Queue() {
delete[] elements;
}
};
#endif
Any ideas?
Took a quick look so but I think the problem is somewhere in your implementation of bool enqueue(Customer).
When you do the following:
Customer c(i);
bool in = q1.enqueue(c);
what is happening in enqueue? Is a copy of Customer being made properly?
Not specifically an answer but I think this will drive you in the right direction or perhaps you can post the code for Customer?
I feel really stupid coming to ask this question here today after bugging everyone yesteday on understanding the algorithm. But I am not looking at this thing straight anymore. Anyways, it is a knapsack probled, solved with memoization and dynamic progrmming. The problem is that the printout of my answers is not matching the requierements.
All I want is a second look at it and if someone can point me where I am wrong at.
Appreciated for all the help.
This is the ProfitHeader.h file
#ifndef PROFITHEADER_H_
#define PROFITHEADER_H_
#include <string>
#include <map>
#include <vector>
using namespace std;
namespace kproblem{
typedef int Money;
typedef int Labor;
struct Resources{
Money liquidity;
Labor officeWork;
Labor programmingWork;
Resources(Money li, Labor of, Labor pro) : liquidity(li), officeWork(of), programmingWork(pro){}
//operator -=
Resources & operator -=( const Resources &rhs ){
liquidity -=rhs.liquidity;
officeWork -=rhs.officeWork;
programmingWork -=rhs.programmingWork;
return *this;
}
//operator< Used to make sure that key elements Match. will not modify (this)
bool operator<(const Resources & rhs) const{
if(this->liquidity < rhs.liquidity)
return true;
else if(this->liquidity > rhs.liquidity)
return false;
else if(this->officeWork < rhs.officeWork)
return true;
else if(this->officeWork > rhs.officeWork)
return false;
//this is the iff conditional
else if(this->programmingWork < rhs.programmingWork)
return true;
else
return false;
}
};
//Global Operator-. This will not modify (this).
Resources operator-( const Resources & lhs, const Resources & rhs ){
return Resources(lhs.liquidity - rhs.liquidity,
lhs.officeWork - rhs.officeWork, lhs.programmingWork - rhs.programmingWork);
}
//This is the Project Struct. It should contain the resources and data from the file.
struct Project{
string name;
Resources resources;
Money profit;
Project(string n, Resources re, Money p) : name(n), resources(re), profit(p) {}
};
//Definition of the ValueMap
typedef map<pair<Resources, vector<Project>::size_type>, pair<Money, bool>> ValueMap;
}
#endif
This is my main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <exception>
#include "ProfitHeader.h"
using namespace std;
using namespace kproblem;
//The following was provided to us on the program
class IO_Exception : public runtime_error
{
public:
IO_Exception(const string & message) : runtime_error(message) { }
};
void readProjects(vector<Project> & projects, const string & fileName)
{
ifstream infile(fileName.c_str());
if (!infile)
throw IO_Exception("Could not open " + fileName);
string oneLine;
unsigned int lineNum = 0;
while (getline(infile, oneLine))
{
istringstream st(oneLine);
lineNum++;
string name;
Money liquidity;
Labor officeWork;
Labor programmingWork;
Money profit;
st >> name;
st >> liquidity;
st >> officeWork;
st >> programmingWork;
st >> profit;
if (st.fail())
{
cerr << "Skipping line number " << lineNum << ": "
<< oneLine << endl;
continue;
}
string junk;
if (st >> junk)
{
cerr << "Skipping line number " << lineNum << ": "
<< oneLine << endl;
continue;
}
projects.push_back(Project(name, Resources(liquidity, officeWork, programmingWork), profit));
}
if (!infile.eof())
throw IO_Exception("Error reading from " + fileName);
}
//Class Best Profit.
//This class will calculate the best possible profit we can get.
Money bestProfit(const vector<Project> & projects, Resources res, ValueMap & valMap,int n){
//initialize the best 2 possible solutions.
Money best1;
Money best2;
Money map; // the map where ou answers are stored
// First check if we are not at the end of the projects
if(n == 0){
return 0;
}
//now we are going to check the best project possible.
//Check the subinstance if it was solved.
if(valMap.find(make_pair(res, n-1)) != valMap.end()){
map = valMap.find(make_pair(res, n-1))->second.first;
return map;
}//check if the subinstance is solved. if it is return the value.
best1 = bestProfit(projects, res, valMap, n-1);//first best possible solution
//check the resources for the last project only. Fopr the second best possible solution.
if(res.liquidity >= projects.at(n-1).resources.liquidity
&& res.officeWork >= projects.at(n-1).resources.officeWork
&& res.programmingWork >= projects.at(n-1).resources.programmingWork){// feasability Check.
//all the above are requiered as it is necessary to check for all of them when doing the calculations.
best2 = bestProfit(projects, res - projects[n-1].resources, valMap, n-1) + projects[n-1].profit;
}
else{
best2 = 0;
}
//after the whole check compare the results and store the best possible result in the map.
if(best1 >= best2){
valMap.insert(make_pair(make_pair(res, n), make_pair(best1,false)));
return best1;
}
else{
valMap.insert(make_pair(make_pair(res, n), make_pair(best2,true)));
return best2;
}
}
//reportBestProfit. This will call Best profit and help us print the final results.
void reportBestProfit(vector<Project> projects, Resources resources){
ValueMap valueMap;
//Variables for the total resources used.
Money liq = 0;
Money ow = 0;
Money pw = 0;
int n = 1000; //number of projects, put here for fast testing
Money bestP = bestProfit(projects, resources, valueMap, n);
//Iterate the valuemap and print the best projects available to us.
cout << "Selected Projects -" << endl;
for(int i= 1; i <= 1000; i++){
//if(valueMap.find(make_pair(resources, i-1)) == valueMap.end()){
if(valueMap.find(make_pair(resources, i))->second.second == true){
//if(valueMap.find(make_pair(resources, i))->second.first != valueMap.find(make_pair(resources, i-1))->second.first){
//cout << valueMap.find(make_pair(resources, i))->second.first; //money
//cout <<" "<< valueMap.find(make_pair(resources, i))->second.second; //boolean
cout << " " << projects.at(i-1).name << " " << projects.at(i-1).resources.liquidity <<" ";//projects
cout << projects.at(i-1).resources.officeWork << " " << projects.at(i-1).resources.programmingWork;
cout << " " << projects.at(i-1).profit << endl;//profit
//}
}
}
cout << "Total Resources Used -" << endl;
//Print the resources consumed.
for(int i= 1; i <= 1000; i++){
if(valueMap.find(make_pair(resources, i))->second.second == true){
liq += projects.at(i-1).resources.liquidity;
ow += projects.at(i-1).resources.officeWork;
pw += projects.at(i-1).resources.programmingWork;
}
}
cout << " " << "Liquidity: " << liq <<endl;
cout << " " << "Office Work: " << ow <<endl;
cout << " " << "Programming Work: " << pw <<endl;
//Print the total Profit.
cout << "Profit: " << bestP << endl;
system("PAUSE");
}
int main()
{
vector<Project> projects;
try
{
readProjects(projects, "Proj5Data.txt");
}
catch (const IO_Exception & ex)
{
cerr << "IO error from: " << ex.what() << endl;
return 1;
}
//these values can be changed for different analysis on projects.
Money liquidity = 200;
Labor officeWork = 450;
Labor programmingWork = 1000;
cout << "Available resources - " << endl
<< " Liquidity: " << liquidity << endl
<< " Office Work: " << officeWork << endl
<< " Programming Work: " << programmingWork << endl;
reportBestProfit(projects, Resources(liquidity, officeWork, programmingWork));
return 0;
}
The project file that contains the projects can be downloaded temporarily here:
https://rapidshare.com/files/459861869/Proj5Data.txt
my guess is the problem is on the valmap find, but I have tried all kinds of combinations and it does not work at all.
Finally this is the final printout I should be getting from this:
But instead I am getting all these other results, including some of the ones I need:
Again thank you for the one that can slap me in the head and say, you FOO, you shouldn't be doing this anymore :).
removing this would get rid of the leading numbers on the second part of the output
cout << valueMap.find(make_pair(resources, i))->second.first; //money
cout <<" "<< valueMap.find(make_pair(resources, i))->second.second; //boolean
cout << " "
the values you print at this point haven't been filtered by and ordered by which is why i think your printing these values
but you don't have code to print "The total resources used -" part
OK, so yes I do have an answer. Is now complete (after edit)
void reportBestProfit(vector<Project> projects, Resources resources){
ValueMap valueMap;
//Variables for the total resources used.
Money liq = 0;
Money ow = 0;
Money pw = 0;
vector<Project> result;
int n = 1000; //number of projects, put here for fast testing
Money bestP = bestProfit(projects, resources, valueMap, n);
//Iterate the valuemap and print the best projects available to us.
cout << "Selected Projects -" << endl;
// this loop just iterates through the values, it does not check the initial resources.
for(int i= 999; i > 0; i--){
//if(valueMap.find(make_pair(resources, i-1)) == valueMap.end()){
//check first If I still have resources available
if(resources.liquidity >=0 && resources.officeWork >= 0 && resources.programmingWork >= 0){
if(valueMap.find(make_pair(resources, i))->second.second == true){
//when I find the first true, I need to substract the resources of it from the base resources,
//to ask the question again.
resources.liquidity -= projects.at(i-1).resources.liquidity;
resources.officeWork -= projects.at(i-1).resources.officeWork;
resources.programmingWork -= projects.at(i-1).resources.programmingWork;
//Push the results into a vector for the printout
result.push_back(Project(projects.at(i-1).name,
Resources(projects.at(i-1).resources.liquidity,
projects.at(i-1).resources.officeWork,
projects.at(i-1).resources.programmingWork),
projects.at(i-1).profit));
//Also in one shot add together the resources used
liq += projects.at(i-1).resources.liquidity;
ow += projects.at(i-1).resources.officeWork;
pw += projects.at(i-1).resources.programmingWork;
}
}
}
//Print the saved vector in reverse order
for(int size = result.size(); size != 0; size--){
cout << " " << result.at(size -1).name;
cout << " " << result.at(size -1).resources.liquidity;
cout << " " << result.at(size -1).resources.officeWork;
cout << " " << result.at(size -1).resources.programmingWork;
cout << " " << result.at(size -1).profit << endl;
}
cout << "Total Resources Used -" << endl;
////Print the resources consumed.
cout << " " << "Liquidity: " << liq <<endl;
cout << " " << "Office Work: " << ow <<endl;
cout << " " << "Programming Work: " << pw <<endl;
//Print the total Profit.
cout << "Profit: " << bestP << endl;
system("PAUSE");
}
Basically I was not substracting the resources, so I was always having over resources, but once I did that viola! it works. Thank you guys for looking at it, I guess I just needed inspiration this morning.