0

I'm stuck on the logic in pset3 won() function. Apparently, the function just doesn't return true no matter what. Here is my code.

bool won(void)
{
    int n = 1;
    //iterate over the board
    for (int i = 0; i < d; i++)
    {
        for(int j = 0; j < d; j++)
        {
            //check to see if last space is 0
            if (board[d-1][d-1] != 0)
            {
                return false;
            }
            //check if number increasing
            else if (board[i][j] != n)
            {
                n = n+ (d*i)+j;
                return false;
            }
        }
    }
    //continue to check last row after this line
    return true;
}

Please note that I am including n in hope that, at board[0][0], n =1, board[0][1], n = 1+ 3*0+ 1 =2; board[1][0], n = 1+ 3*1+0 = 4; board [1][1], n = 1+ 3*1+ 1= 5.

Thank you for any help you can offer.

1

First, note that you change n only if something is wrong.

Let's suppose that board [0][0] = 1 as it should be. Then, this condition

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

doesn't work so you still have n == 1, and continue to check board[0][1]. Suppose it is 2 as it should be. You check

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

as n is still == 1, board[0][1] == 2, condition is true so you return false and game is over

also, even if you correct this, you still have quite a misleading assignment:

n = n + (d*i) + j;

indeed, if you checked successfully n = 3 for board[0][2], next iteration it's going to be n = n + (d*i) + j = 3 + (d*0) + 2 = 5, while you need to check n == 4.

try to use just n = n + 1 or (d*i) + j without n = n +, if you'd prefer

| improve this answer | |
  • Whoops! Too focused on n value and forgot that huge logical mistake there. – Ha Tran Jun 19 '17 at 9:59

You must log in to answer this question.

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