0

I am working through the Game of Fifteen and have almost completed it, but the program does not return an exit code of 0, which I'm almost certain is due to my won function. Here's my code:

bool won(void)
{
for(int x = 1; x < d*d; x++)
{
    for(int i = 0; i < d; i++)
    {
        for(int j = 0; j < d; j++)
        {
            if(board[i][j] != x)
            {
                return false;
            }
        }
    }
}
return true;
}

And here's the check50 output: https://sandbox.cs50.net/checks/85d30ea5f0364778a3186595b9385731

Any help would be greatly appreciated. Thank you!

1 Answer 1

1

Well, the sandbox output says its working, but I'm thinking that it isn't the result of your program. Having said that, let's look at your won() code.

In short, this code will always fail. It will start by setting x=1 and then trying to compare every tile to x before incrementing x. So, if the board is right, it will compare x to the first tile, see that it is 1, and move to the next tile. Since the second tile is 2, and 2 != 1, it will immediately fail.

To further explain, let's imagine commenting the return false out so that it doesn't return. The code would start by setting x=1, then it would run through every tile and do the comparison. After checking every tile, it would then return to the outer loop, increment x to 2, and then run through every tile again, and so on.

Incrementing x with a for loop simply doesn't work. x needs to be incremented after every successful comparison of x to a tile. I'll leave it to you to figure out how to implement. Just keep it simple. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thank you Cliff!
    – dmz
    Commented Jun 6, 2017 at 13:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .