0

My move function generally works properly, but every so often it adds an extra 0 in to the table, so that there are two. Both can then be moved around. I can't figure out what corner case I haven't accounted for that is causing this bug.

bool move(int tile)
{
// TODO
for (int i = 0; i < d; i++)
{
    for (int j = 0; j < d; j++)
    {
        if (board[i][j] == tile)
        {
            if (board[i + 1][j] == 0 && i + 1 < d)
            {
                board[i][j] = 0;
                board[i + 1][j] = tile;
                return true;
            }
            else if (board[i - 1][j] == 0 && i - 1 < d)
            {
                board[i][j] = 0;
                board[i - 1][j] = tile;
                return true;
            }
            else if (board[i][j + 1] == 0 && j + 1 < d)
            {
                board[i][j] = 0;
                board[i][j + 1] = tile;
                return true;
            }
            else if (board[i][j - 1] == 0 && j - 1 < d)
            {
                board[i][j] = 0;
                board[i][j - 1] = tile;
                return true;
            }
        }
    }    

}
    return false;
}

Where is the flaw in my logic?

0

You had the right idea, but only implemented it half-correctly. Look at this:

else if (board[i - 1][j] == 0 && i - 1 < d)

When i = 0, what is i-1? Seems like i-1 will always be less than d, but maybe this isn't what you want to check? Same for j. This should get you going. ;-)

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

3
  • I'm not sure I follow. If i = 0, this condition will never be true, because there is no board[-1]. Unless the garbage value does == 0? Then I'm in trouble. Is that the issue? the < d condition checks whether the value is on the board. I guess it shouldn't let negative values pass, because they also aren't on the board – Avishai Fuss Feb 18 '16 at 14:36
  • I think I'm touching a 0 from a terminator character of the previous number in memory. I added this condition, I'm not sure why it doesn't solve the problem else if (board[i - 1][j] == 0 && (-1 < i - 1 < d)) – Avishai Fuss Feb 18 '16 at 15:47
  • While it works in mathematics, the form of a<x<b isn't valid syntax in programming. It would have to be a<x && x<b. However, when testing for i-1, it isn't necessary to check that i-1<d. By definition in the for loop, i will always be less than d and therefore i-1 is always even smaller. – Cliff B Feb 18 '16 at 16:14

You must log in to answer this question.

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