0

The won() function, which I thought was pretty straightforward, initially gave me some trouble. I had it trying to evaluate the if statement seen below in a loop that iterated over each position of the board.

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

        }
    }

    return true;

}

If the value at the given coordinate didn't match what was expected, (formula) OR Zero, then false. But if we find our expected values, we would iterate all the way through the loop and return true. But this wouldn't work. I ran printf to check values against my if statement check and everything was as expected. When 1 was at coordinates [0][0], my if statement was checking to see if the value there was other than 1 or zero. So it should have continued the loop, but instead it returned false.

I had to modify the code to the following before it would work.

bool won(void)
{
// TODO
for (int i = 0; i < d; i++)
{    
    for(int j = 0; j < d; j++)
    {   
        if(board[i][j] == (j + 1) + (i * d) || board[i][j] == 0 )
        {
            continue;
        }    
        else
            return false;
    }
}

return true;

}

Can anyone shed some light on this? I'm guessing that I've misunderstood some of the finer points of if statement logic. But "if not 1 or zero, return false" seems straightforward.

0
if(board[i][j] != (j + 1) + (i * d) || board[i][j] != 0 ) return false;

Let's look carefully at this test. Assume board[0][0] == 1. The test has two parts. The first part checks that the value is 1 so the first part is false. BUT, the second test checks it see if the tile != 0. Since the tile is 1, and 1 != 0, the second test is true. Since there's an OR that joins the two tests, if either is true, then the whole is true, and it returns false.

When doing complex logic tests, it's necessary to look at all of the possible results. There are semester long college courses on the topic, so I'll just suggest that you google "logic table" for a start. ;-)

There are lots of ways to get there. You found one. Another would be this:

    if(   !(board[i][j] == (j + 1) + (i * d) || board[i][j] == 0 ) )
    {
            return false;
    }

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

| improve this answer | |
  • Thanks, Cliff. I was aiming for the semantics of your example which reads like more of a XNOR,.... I think. Anyways, thanks again! – Scott J. Aug 16 '17 at 20:04

You must log in to answer this question.

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