pset3 Fifteen: Function won won't win

After running the check50, errors below appear:

``````:( 3x3.txt wins the 3x3 board
\ expected an exit code of 0, not a prompt for input
:( 4x4.txt wins the 4x4 board
\ expected an exit code of 0, not a prompt for input
``````

I tested with .txt and instead of win, it says Move tile: Retry. Illegal move. See my function won:

``````bool won(void)
{
int counter = 1;

for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{

if (board[i][j] == counter && counter < (d*d))
{
counter++;
}
else
return false;

}
}
return true;

}
``````

This problem is showing up over and over. When the board[][] array indexes are set by d, and i and j must both be less than j, what happens when i+1 or j+1 = d? In other words, say that d=3 and i = 2. Now look at this:

``````else if (board[i + 1][j] == 0)
``````

With these numbers, i+1 = 3 and d=3, but the index must be < 3! Same logic applies to i-1 going to -1. In all these cases, the system won't automatically generate an error, but it will look where it thinks the array element can be found. That means it's going to look at another memory location that is probably in use by something else. If it happens to be data that passes the given test, it's going to do a swap and move a tile out of the array.

The array indexes MUST NOT be allowed to be out of the valid range!

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

• Ok so I changed my codes with your logic (see below) but it keeps on changing the top left number. i/j + 1 <else if (board[i + 1][j] == 0 && i + 1 < d)> i/j - 1<else if (board[i][j - 1] == 0 && j - 1 >= 0)> Mar 5, 2016 at 19:54