So our teacher gave us the task to wirte a programm which checks for a given input if a race track can be completed.
The chars used are "/" for going uphill which slows the car by 1, "\" for going downhill, speeding the car up by 1 and "_" for a plain in which the driver has to decide whether he speeds up or slows down. The goal ist to complete a given track, having a speed of 0 at the end.
1 2
|
\\/__/ -> possible
\\/__ -> not possible
|
The speed of the car can be 0 during the race, if the following char is a "\" or a "_".
The drivers can now walk along the track and evaluate whether they'll manage to finish it with a speed of 0 or not. Limitations are that I can read through the parcour exactly once, and may not "jump" from one part of the string to another, as well as using the least possible amount of memory, as the drivers are bad at memorizing things.
So far my code looks like this, but I think I violated one of the limitations, as I check what
parcourPart[i + 1]
looks like...
Does anybody have an idea how to solve this problem?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include <iostream>
#include <fstream>
#include <string>
#include<vector>
#include <stdlib.h>
bool check(std::string parcour);
int evaluatePart(std::string parcourPart, int currSpeed);
int main(int argc, char** argv)
{
std::string line, parcour;
std::ifstream myfile("parcourstest.txt");//argv[1]);
bool canFinish = false;
if (myfile.is_open())
{
while (std::getline(myfile, line))
{
parcour += line;
}
myfile.close();
}
else std::cout << "Unable to open file";
parcour += "#";
if (parcour.size() < 102) {
std::cout << parcour;
}
canFinish = check(parcour);
if (canFinish) {
std::cout << "\b I can do that!";
}
else std::cout << "\b No way!";
return 0;
}
bool check(std::string parcour) {
int i = 0, speed = 0;
std::string part = "";
while (parcour[i] != '#')
{
part += parcour[i];
if (part.size() == 5 || parcour[i+1]=='#') {
if (evaluatePart(part, speed) > -1) {
speed = evaluatePart(part, speed);
}
else return false;
part.clear();
}
i++;
}
if (speed > 0 || speed < 0) {
return false;
}
else
{
return true;
}
}
int evaluatePart(std::string parcourPart, int currSpeed) {
for (int i = 0; i < parcourPart.size(); i++)
{
if (parcourPart[i] == '\\') {
currSpeed += 1;
}
else if (parcourPart[i] == '/' && currSpeed != 0)
{
currSpeed -= 1;
}
else if (parcourPart[i] == '/' && currSpeed == 0)
{
return -1;
}
else if (parcourPart[i] == '_')
{
if (currSpeed > 0 && parcourPart[i+1] != '/') {
currSpeed -= 1;
}
else {
currSpeed += 1;
}
}
}
return currSpeed;
}
|