Debugging code for won function in game of fifteen

My code for won seems have correct logic but is not working.I could only check for 9 tile game as I only solved this so far but gametes not break out of loop and asks again tilt move after the winning configuration.

bool won(void)

{
int checkWon = 0;

int k = 0;

for (int i = 0; i < d; i++)
{
for (int j = 1; j <= d; j++)
{
if (board[i][j] != (i+j+k)%(d*d))
{
checkWon = 1;
}
}
k = k+d-1;
}
if (checkWon == 0)
return true;
else
return false;

}

Have you worked out what happens with paper and pencil? Look at what happens when you check the second row of a 3x3 board. For this, i=1, j=0, d=3 and the tile should be 4. Now, fill in the following two lines:

k = k+d-1;
if (board[i][j] != (i+j+k)%(d*d))

Now, let's plug in the values:

board[1][0] = 4
k = 0 + 3 - 1 = 2
(i+j+k)%(d*d) = (1+0+2) % 9 = 3
4 != 3

Simply put, the formula is incorrect. Only the first row will ever check out as correct.

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

• I think the formula is correct and I checked it on paper; My code starts j from 1 and goes up to d while my i starts from 0 to d-1. – rasdocus Mar 4 '17 at 2:21
• I got it!, even though I was incrementing J from 1 and not 0, it was messing up my board[i][j] as it was checking board[0][1] on the very first cell and not board[0][0]. – rasdocus Mar 4 '17 at 2:41
• I changed it to board[i][j-1] and the problem was solved, thanks for your help – rasdocus Mar 4 '17 at 2:42
• Yeah, I should have looked closer. I completely skipped over j starting at 1 and assumed it started at 0. Your change definitely will work, but it has about 2 or 3 extra calculations in each loop. Wouldn't it make more sense to have j go from 0 to d-1, the same as i, and to change the formula to k = k+d;? – Cliff B Mar 4 '17 at 2:46
• that would be more elegant,i agree, thanks – rasdocus Mar 5 '17 at 2:41