0

yet again. i started working on the game of fifteen, i got it to work. But i had a lot of struggle with the won function. although it now works, i still don't know why it works. it was pretty much guess work until i got it to work, i would like to know why the this snippet of code work.

bool won(void)
{
    // TODO
    // check to see if the game is won;
    int counter = 1; // counter for checking;

    for (int row = 0; row < d; row++) { // for each row
        for (int col = 0; col < d; col++) { // for each col
            // make sure the board matches a winning board
            if (row == d-1 && col == d-1) {
                return true ;
            }

            if (board[row][col] != counter) {
                return false;
            }

            counter++;
        }
    }
    // if there is a problem return false;
    return false;
}

so how would the computer know what fork in the road to follow when implementing the check function.

also why wouldn't this code work for that and how can i make it work

bool won(void)
{
    // TODO
    // check to see if the game is won;
    int counter = 1; // counter for checking;

    for (int row = 0; row < d; row++) { // for each row
        for (int col = 0; col < d; col++) { // for each col
            // make sure the board matches a winning board
            if (board[d-1][d-1] == 0) {
                return true ;
            }

            if (board[row][col] != counter) {
                return false;
            }
            counter++;
        }
    }
    // if there is a problem return false;
    return false;
}

why would'nt that code work?

thanks for taking the time to read this, and helping me out. loving this course by the way

1 Answer 1

1

row == d-1 && col == d-1 would be true on the last iteration of both outer (row) and inner (col) loop. At that time, you've checked all but the last tile to be in right order. If those are, the last one also is.

Second version would return true if last empty tile is in the lower right, independent of the order of the other tiles.

You could fix the second for example by removing the first if, changing the second to if (board[row][col] != counter % (d*d)) {, and returning true instead of false after the loops. With %(d*d) the counter would start at 0 again when reaching d*d (which does not exist as a tile)

You must log in to answer this question.

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