c++ stack maze solving program - c++

I wrote a program to generate a maze and to solve it, however it has some bug in the solving part.
It forms a square maze like 5*5 or 16*16.
The maze starts at (0,0 in a 2D array, and ends at (size()-1, size()-1).
I use '1' to indicate the path to end.
You can see from the picture below there are some unwanted '1' although the program can find the exit.
Excuse me everyone, I really can't debug this. Can anyone help me or guide me?
Much appreciated!
The screencapure is here. Im not allowed to post image directly
https://photos-1.dropbox.com/t/0/AADjdwSgmLdVKCZrI1C-gDvwZ9ORj0rGbv3UJ7AYqXWeuA/10/7014161/png/2048x1536/2/1355295600/0/2/bug.png/5sQR3E_jcow4lWIy9cFf2FYbmwl0C_sd2cfCyMPe0MU
My code is in here
https://www.dropbox.com/s/vldkcv4fy6bp1ff/Source.cpp
PROBLEM SOLOVED
Thanks everyone
my original code for solving the maze was
`else if (randomNum==1) {
if (y+1<myMaze.size() && !myMaze[x][y+1].left && !myMaze[x][y+1].visited)
{
y++;
myMaze[x][y].truePath=true;
myMaze[x][y].visited=true;
s1.push(myMaze[x][y]);
randomNum=rand()%4;
}
else
{
rightBusted=true;
randomNum=rand()%4;
}`
Then I just add these codes inside the if-statement to reset the bool variables to false, then the problem solved
downBusted=false;
rightBusted=false;
topBusted=false;
leftBusted=false;

You can debug this, man. Here's how. You already have the tools you need to do it; all they need is a little tweaking.
Your best tool for debugging this is your displayMaze() routine. You just need to add two optional parameters to it to turn it into a powerful debugging tool:
void displayMaze(const vector < vector<Cell> >& arr, int curX=-1, int curY=-1)
{
.
.
.
Now if a caller omits curX & curY, the compiler fills in the defaults of -1. Now later on in that function, print a different character to indicate the "current maze position". Here's how I did it, which "seems to work" but I'm not guaranteeing it because I didn't bother to actually understand your logic:
if (curX>=0 && curY>=0 && curX==i/2 && curY==j) // ++++++++++++
cout << " * "; // * means "current position" // ++++++++++++
else if (!arr[i/2][j].truePath)
cout << " ";
else
cout << " 1 ";
Now you have a formidable debugging tool built into your program. When main() calls it without the two extra parameters, no asterisk is printed. But when you call it from solveMaze(), you can specify the "current location" so it will flag that location with '*'. In solveMaze(), add a couple variables for keeping track of the "current location"...
int x=0, y=0;
int curX=x, curY=y; // ++++++++++++++++
...then, at the top of your loop, just call your formidable debugging tool so you get the current status of your overall solution as it progresses, step-by-step:
int i=0;
while (!exitFound)
{
displayMaze(myMaze, curX, curY); // +++++++++++++++++
.
.
.
Now, wherever you change what you consider to be the "current location", just update curX and curY accordingly, and your debug tool will keep you updated so you can see the solution as it unfolds graphically (well, pseudo-graphically). You might even add debug cout messages at key logic decision points, so you can correlate those decision points with the solution you see unfolding, so you can see if/when there's a problem. And if you find a problem, you can scroll back up in your output to see where things went wrong.
Good luck!

Related

C++: Why/How a Break Statement Works In This Code?

I have started to use C++ programming language as a complete beginner. With the aim of becoming a better programmer for my STEM degree and with the goal of competitive programming in mind. I have started Functions and Loops in C++ recently and there was a problem I was not sure how to approach.
The probelem: "Write a function to check whether a number is prime"
My Approach:
-> I wanted to implement it on my own so I didn't want to copy paste code online where others have used functions with return type bool.
-> Here is the final version of my code that works:
void prime(int k){
for(int k1=2;k1<k;k++){
if(k%k1==0){
cout<<"int is not prime"<<endl;
break;
}
else{
cout<<"int is prime"<<endl;
break;
}
}
}
->I would then call this in int Main() and get the user to input integers and so on.
-> The above code was due to many trial-and-errors on my part and my thought process was as follows: 1)if i don't include the "break;" statement my code results in an infinite loop 2)I needed a way to stop my code from going toward an infinite loop 3) I remember a topic covered in the functions segment of this website , where we can use it to terminate a loop at will. Thats why i incorporated it into my code to produce the final version
My Question:
Can someone explain how the break; statement is working in the context of my code? I know it produces my desired effect but I still haven't gotten an intuition as to how this would do my work.
Many online resources just cite the break statement as something that does so and so and then gives examples. Without going through the code mechanics. Like how a loop would be going through its conditions and then when it encounters the break; statement what does it do? and as a consequence of that what does it do to help my code?
Any advice would be helpful. I still couldn't wrap my head around this the first time I encountered it.
In your case if k % k1 does not show that the k1 being a factor of the k, the loop is broken after the print statement. If the k % k1 does show that the k1 being a factor of the k, it also breaks out of the loop.
So, either of the break statements leads to the loop termination on the first iteration here. If you test for whether a number is being a prime, it does not work.
In essence, you don't need either of the break statements here. They are mostly forced here. Take a look at the following approach:
#include <iostream>
#include <cmath>
bool prime(unsigned k){
if (k != 2) { // Direct check, so to remain similar to the OP's structure of the code
unsigned up_to = sqrt(k) + 1; // Calculate the limit up to which to check
for (unsigned i = 2; i < up_to; ++i) {
if (k % i == 0) {
std::cout << "Is not prime" << std::endl;
return false;
}
else std::cout << "Checking..." << std::endl;
}
}
std::cout << "Is prime" << std::endl;
return true;
}
// Note, we can check just up to the square root of a k
A note on the behavior of the break
The fact that it breaks out the the closest loop to it - has crucial nature for nested loops (all of them: for, while, and do while):
while (/* condition 1 */) // Outer loop
while (/* condition 2 */) // Inner loop
if (/* condition 3 */) break;
Here if the condition 3 is satisfied, the break will lead to break out of the Inner loop but the Outer loop will still continue to iterate.
For more, you may be interested in "How to exit nested loops?" thread. It addresses your second question.
Analogy... I found it in the last place I looked... like always!
Looking for your keys is the LOOP you are in... when you find them... you BREAK out and move on to another task... like maybe getting into your car...
SO if you are IN your car and know your car is where you left your keys... then you are in the PROCESS of getting prepared to drive away... BUT that process requires keys... THUS you change modes/focus and begin a cyclic process of looking for keys... when found to BREAK that searching process IMMEDIATLY and resume what your were doing.
MANY people would make use of the RETURN instrucion in your code pattern... in place of the break! Both do the same thing... however the RETURN is more descriptive english... and one should be concerned with the programmer behind him... Also a bit of digging might show how one is more efficient than the other...

C++ how to move Text with ncurses.h?

C++ how to move Text from off screen to inside the terminal (animation 20/50 millisec.) and then stop the animation. with ncurses.h ? pls with examples
with perhaps a loop that increases the X coordinate from (x = 0-number characters text-1) to (x = 2 or 1), for each Line of text containing the color.
let me explain: the previous sentence no longer moves (it remains stationary on X2 coordinates), the sentence of now makes the entry animation, as soon as the animation ends, it becomes the still sentence together with the other preceding sentences. moves the next one, and continues the loop until it is finished.
I didn't get the result I wanted: (this is the code)
#include <iostream>
#include <windows.h>
#include <ncurses.h>
using namespace std;
void tdnVoid(short colore)
{
HANDLE a = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(a, colore);
}
int main()
{
initscr();
int b = 0;
while (b != 256)
{
b++;
refresh();
move(0, 0);
tdnVoid(b);
cout << b << ". ■ ";
cout << "\n";
if (b % 16 == 0)
{
cout << "\n";
}
Sleep(100);
}
return 0;
}
☑️the result I wanted (GIF):
Gif Hello World example - GIF
❌the result I got: Gif C++ Program execution, pls help me solve it
NEW EDIT:
according to the documentation, you can use this:
mvprintw(y,x,"your string",); refresh(); but i use and try for like 2 hours, having errors;
pls if someone can help me, you will really help me!
this program may seem useless, but I am using it to learn C ++, once I have learned this, I can use the same function and complicate and do more interesting things. hope you understand me (there are those who created Nokia's Snake game with ncurses, there are those who 3D things that rotate in space) thank pls help me to understand :)
stackoverflow guys. i started stackoverflow bad. sorry for my wrong attitude
(that's why I didn't get an answer)
but luckily I managed to get the result I wanted! I can be of help for you! in the documentation it won't say, but through a while () loop I managed to do it!
int main()
{
initscr();
int x = -1;
while (x < 22)
{
x++;
refresh();
mvprintw(0, x, " C++ colori", 10);
Sleep(300);
}
//other my code
}
before putting refresh (); which is important to update, then mvprintw() which is like a cout << /*from <iostream> library*/ but with mv (mv is move()) ... which is what I wanted !! the first attribute is the Y which are the vertical, and the second attribute is the X that is to move in the same horizontal line.
all separated by commas, attention: I put the x as a variable and not as a number because I made it move through the while loop.
after put the string of characters, remember: put a space before if not you have a result like this
❌output: CCCCCCCCCCCCCC++ colori
with a space before, it appears to be invisible, so it works.
☑️output:                                    C++ colori
after I put Sleep(/*milliseconds*/); remember to put the <windows.h> library
10 is the number of characters, I know you could have done better by automating it with char [] =" your string " and make the program count, but it was was a beta.
===========
remember: if you don't put endwin (); at the end of the loop what you saw in the GIF will happen. on all your next normal code. here my first Bug

C++ - Using specific character input for 'if' statements

I am, for lack of a better word, an absolute programming novice. And as it stands, I've been flung head first into programming something in two or three languages.
As part of an assignment, we have been tasked with essentially recreating a heads/tails flip, in the form of a random chance game.
The way it works is the player has ten credits to start off with. They are asked to input a wager, and then they are asked heads or tails. Picking either heads or tails sets off a number generator, and depending on the value, they may well end up winning or losing their wager.
I coded a similar version of this using HTML/CSS/JS, and it works. I'll leave a puush link to the file so you can view it yourselves to get an idea of what I'm trying to do: http://puu.sh/bP2V7/2ef63f4a1c.html
I'm trying to do, functionally, the same thing in C++ in the form of a command application. I know the code I'm using works fine, and it compiles without much of a hitch. It's a bit annoying that it closes down rather than resetting to a previous line, but that's a hurdle I'll jump over when I get to it.
I had a look around, and to be honest, whilst a few of the things may well work, I'm admittedly relatively clueless and some of the programmer speak kinda flies over my head.
It's probably because I'm being thrown into it and I'm not used to it yet, but as it stands, I need your help.
My code simply works as follows (simplified to save time):
int main()
{
int points, wager;
points = 10;
output "HEADS OR TAILS?";
if (player has 1 point or more)
{
output "Input wager";
input wager value;
output "Wager is (player input)";
output "Heads or Tails?";
input h or t; //This was what I wanted
if (player selects 'heads') //For sake of simplicity, the code
{ //here will account for both heads
int heads; //and tails.
srand(NULL);
heads = random number 1 and 2;
if (heads = 1)
{
output "HEADS!";
output "You win 'wager'!";
points = points + wager;
}
if (heads = 2)
{
output "TAILS!";
output "You lose 'wager'!";
points = points - wager;
}
}
}
if (player has 0 points)
{
output "GAME OVER";
}
}
What I want to do is have the user input either an 'h' or a 't' to determine whether or not they want heads or tails.
In your programming class, they will have told you what they expect you to use as tools for input and output, eg char inputChar; cin >> inputChar; or similar. Use whatever they told you to use in the style they want you to use, eg
cout << HEADS_OR_TAILS_PROMPT;
char inputChar;
cin >> inputChar;
switch(inputChar) {
case 'h':
{
... // code for the heads case
break;
}
case 't':
{
... // code for the tails case
break;
}
default:
// whatever you want to do if they didn't input a valid option
}
Although, to be honest, asking your professor is going to get you a better answer for what the grader is expecting than asking us is.

C++ After Function Call and Function Completion, Game Crashes Entirely

I've been having an issue with a game I've been making in my C++ game programming class for school. For some reason, after calling a function which I'm using to manage the inventory based stuff, the function seems to complete and work (I think this because I put in cout commands at the end of it and they printed correctly, also the function runs twice in a row, and they both run), my entire game crashes and doesn't reach the next line. I tried commenting out all the code in the function and it still crashed. I commented out the function calls and it worked, but I still can't tell what is wrong with it. I'll put the code for the function and the section were I make the calls:
string inventoryFunction(int h, string ab)
{
if(h == 1)
inventory.push_back(ab);
else
if(h == 2)
{
for(int i=0; i < inventory.size(); i++)
{
if(inventory[i] == ab)
inventory[i].erase();
}
}
else
if(h == 3)
{
cout << inventory[0];
for(int i=1; i < inventory.size(); i++)
cout << ", " << inventory[i];
}
}
The function call:
if(answer.find("village") != string::npos)
{
cout << endl;
cout << "While looking around your village,\nyou found a stone sword and a cracked wooden shield!" << endl;
inventoryFunction(1, "stone sword");
inventoryFunction(1, "cracked wooden shield");
cout << "Would you like to set off on your adventure now?" << endl;
cin >> answer2;
capitalizeLower(answer2);
Not sure there's anything there likely to cause a crash, my advice would be to single-step your code in the debugger to see where it's falling over. It's quite possible the bug is somewhere totally different and it's just being exacerbated by the function calls modifying the vector.
That's the nature of bugs unfortunately, you can never really tell where they're actually coming from without looking closely :-)
However, there are a couple of issues with the code that I'd like to point out.
First, with regard to:
inventory[i].erase();
That doesn't do what you think it does. inventory[i] is the string inside your vector so it's simply erasing the string contents.
If you want to remove the string from the vector, you need something like:
inventory.erase (inventory.begin() + i);
Second, I'd tend to have three separate functions for addToInventory, removeFromInventory and listInventory.
It seems a little ... unintuitive ... to have to remember the magic values for h to achieve what you want to do, and there's no real commonality in the three use cases other than access to the inventory vector (and that's not really reason enough to combine them into the same member function).
On top of that, your function appears to be returning a string but you have no actual return statements and, in fact, none of the three use cases of your function require anything to be passed back.
The signature is better off as:
void inventoryFunction(int h, string ab)
In terms of the second and third points above, I'd probably start with something like:
void addToInventory (string item) {
inventory.push_back(ab);
}
void removeFromInventory (string item) {
for (int i = 0; i < inventory.size(); i++) {
if (inventory[i] == ab) {
inventory.erase (inventory.begin() + i);
break;
}
}
void listInventory () {
cout << inventory[0];
for (int i = 1; i < inventory.size(); i++)
cout << ", " << inventory[i];
}
You may also want to look into using iterators exclusively for the second and third functions rather than manually iterating over the collection with i.
It'll save you some code and be more "C++ic", a C++ version of the "Pythonic" concept, a meme that I hope will catch on and make me famous :-)
So by changing the inventoryFunction to a void function like #Retired Ninja said, the crash has stopped occurring and now the program is working great.
Also, #paxdiablo pointed out that I was using the inventory[i].erase() thing incorrectly, so thanks a bunch to him, because now I won't have to come back on here later to try to fix that :D
string inventoryFunction(int h, string ab)
should return a string but does not have any return statements. Of course it works, after you change it to a void function, which correctly does not return anything. Interesting is, that you are able co compile this code without an error - normally a compiler would show you this problem.

Insert map into vector fails second time

I have an error I couldn't figure where it occues on the following:
I'm acutally using a map with vectors in it:
map<vector<string> , vector<string> > parameterMap;
because I need a few of them (how many is decided on runtime) I put them into a list (vector):
vector declaration on head of method:
vector<map<vector<string> , vector<string> > > listedParameterMap;
insertion of a map into the vector:
listedParameterMap.insert(listedParameterMap.end(), 1, parameterMap);
This procedure works fine on the first time. The second time (map is filled correctly) it down't work.
I noticed a thing: I give out the size of the map:
cout << "listedParameterMap " << listedParameterMap.size();
it shown size is 2 after the second time, the watch says it still 1.
It also shows me wired content:
Screenshot:
Last should contain something looking like First
The second map which is inserted is defently filled correctly.
Same for the vectors: part1_input and part2_output
Code:
for (unsigned int index = 0; index < part1_input.size(); index++) {
map<vector<string> , vector<string> > parameterMap;
parameterMap.insert
(pair<vector<string> , vector<string> > (part1_input[index], part2_output[index]));
listedParameterMap.insert(listedParameterMap.end(), 1, parameterMap);
cout << "listedParameterMap " << listedParameterMap.size();
}
I really would appreciate any ideas why this happens...
EDIT:
"Solution" was printing the stuff out. The watch-window isn't displaying the correct values. That means my Problem is caused somewhere else. But this here is anwsered. Thanks to anyone how tried to help me!
I would like to see a test where you output something from your collections to see if you are seeing what you think you should see. Actually why not write a proper unit test?
You are passing a lot of collections around by value. This can be quite expensive, but in addition, you may be updating something that is a copy of what you think you are actually updating, and then not seeing the results in the original.
I would not pay too much attention to values in Visual Studio's "watch" window, particularly if you are running an optimised build.