0

I'm currently working on pset3 game of fifteen, and my move function is not working. Below is my code for move().

bool move(int tile)
{

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)
            {
                int tmp = board[i][j];
                board[i][j] = board[i + 1][j];
                board[i + 1][j] = tmp;
                return true;
            }
            if (board[i][j + 1] == 0)
            {
                int tmp = board[i][j];
                board[i][j] = board[i][j + 1];
                board[i][j + 1] = tmp;
                return true;
            }
            if (board[i - 1][j] == 0)
            {
                int tmp = board[i][j];
                board[i][j] = board[i - 1][j];
                board[i - 1][j] = tmp;
                return true;
            }
            if (board[i][j - 1] == 0)
            {
                int tmp = board[i][j];
                board[i][j] = board[i][j - 1];
                board[i][j - 1] = tmp;
                return true;
            }
        }


    }
}

return false;
}

I have accounted for the '0' tile being above (board[i + 1][j]), below (board[i - 1][j]), left (board[i][j - 1]), and right (board[i][j + 1]). I used the following swapping method to swap the tiles.

int tmp = a;
int a = b;
int b = tmp;

However, when I run the program and input a tile to move, some (not all) of the numbers just turn to 0 (leaving the original 0 untouched as well) instead of actually swapping the tiles. Here is an excerpt:

7  0  0 
8  0  0 
5  4  3 

Any help would be appreciated. Thanks!

2

It looks like you didn't account for the corner cases where the blank is on the edge of the board. In other words, when you try to swap, i or j could go out of range, essentially swapping with something undefined and off the edge of the board. For instance, if the blank is in the bottom right corner and it tries to swap with i+1 or j+1, it will swap with undefined data.

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

4
  • Hey Cliff, thanks for your help! However, I have been working at it for a while now and have no idea how to implement that...
    – Alif Munim
    Jan 13 '16 at 22:29
  • Hint: can i+1 ever be >= d and reference a valid element?
    – Cliff B
    Jan 13 '16 at 22:43
  • Thanks so much for your advice, I've got about half of those frowns to turn upside down now -- but I'm facing another problem now. All numbers except the number 2 are working properly. As in even if it is an illegal move, the 2 becomes a 0 and the original 0 remains in its place. Very confusing!
    – Alif Munim
    Jan 17 '16 at 8:15
  • sounds like you're treating 2 as a special case.
    – Cliff B
    Jan 17 '16 at 8:40

You must log in to answer this question.

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