0

This is the code for the won() function.

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

            else if (counter<(d*d)-1)
            {
            counter++;
            }
        }    
    }
    return true;
}

Everytime I use the ./fifteen 3 < ~cs50/pset3/3x3.txt command when the won function should return ftw, it instead prompts for an input and returns illegal move

1

This won function won't work, imagine what would happen for i == d-1 and j == d-1 on a solved board. counter then would be d*d-1, and board[i][j]!=counter would be 0!=d*d-1, leading to the solved board to be rejected.

I used something like

if (board[i][j] != counter % (d*d)) {
    return false;
}
counter++;

with the remainder operator %, which evaluates to the remainder of the division counter / (d*d). That's the same as counter for all fields but the last, and 0 for the last (think of it as a wrap-around).

Also an option might be

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

which ignores the last tile on checking. If you got your swaps right, you know the last tile after examining all the others.

I'm not sure whether an "illegal move" message can be triggered by a faulty implementation of won, I'd expect the cause to be in the move function.

| improve this answer | |

You must log in to answer this question.

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