# Pset3, Game of Fifteen, won, game keeps winning!

for the final part of fifteen, my game wins automatically upon start up and I'm not sure why, please help, thanks.

my code is as follows:

``````bool won(void)

{
//for each row
for (int i = 0; i < d; i++)

{
//for each column
for (int j = 0; j < d; j++)

{
if (board[i][j] != (((d*i) + j) + 1) && board[d-1][d-1] != 0)

{
return false;
}

}

}

return true;

}
``````

Initialize a boolean and initialize it to true before the first `for` loop. Where you put your `return false`, set the variable to false. Then, at the end where you have `return true`, return the variable.

• Thanks, but why? – Arhaz Jul 14 '17 at 0:11
• Not quite sure, but that seemed to be the only solution...sorry – Sam Devo Jul 14 '17 at 0:25
• it doesn't work – Arhaz Jul 14 '17 at 0:31
• You must have deted or altered the code in main function. Check for the win condition there. – MIB Jul 14 '17 at 2:33
• To build on MIB's answer above, make sure all you've done is modify the helper functions below main. Your check for winning appears to be correct, though I might be missing something glaringly obvious. – Coby Z Jul 14 '17 at 16:21

OK so I know why the old code didn't work.

Its because at the start of the game, the first if condition is always met i.e. none of the integers are correct, then the second if condition is checked and this fails because the last integer is 0, at both the start and end of the game. Thus always returning true immediately after start up.

I adapted the code and finally made it work (and pass check50), although the new code is quite cumbersome.

It involves removing the second if condition and using a new logic: that the last integer of the 2D array need not be checked because if all the other values are in the correct space, then the last one must be 0 (or '_').

This can be done by adapting the for loops so as to ensure that the last integer is not checked.