# Pset 3: Fifteen - Moving up and down but not left or right?

I am running into problems with fifteen. Specifically, the move function. I can make numbers move up and down, but somehow I've messed up the left and right and I'm not sure how. When I try, it sets the current tile to zero correctly, but doesn't set the chosen number to the old blank space.

In the code snippet below, I use y for the rows and x for the columns.

``````bool move(int tile)
{
// TODO

int boardx;
int boardy;
bool found = false;

for (int y = 0; y < d; y++)
{
for (int x = 0; x < d; x++)
{
if (board[y][x] == tile)
{
boardy = y;
boardx = x;
found = true;
}
}
}

if (!found)
{
return false;
}

if (boardy > 0)
{
if (board[boardy - 1][boardx] == 0)
{
board[boardy - 1][boardx] = tile;
board[boardy][boardx] = 0;
return true;
}
}
if (boardy < d)
{
if (board[boardy + 1][boardx] == 0)
{
board[boardy + 1][boardx] = tile;
board[boardy][boardx] = 0;
return true;
}
}
if (boardx > 0)
{
if (board[boardy][boardx - 1] == 0)
{
board[boardy][boardx - 1] = tile;
board[boardy][boardx] = 0;
return true;
}
}
if (boardx < d)
{
if (board[boardy][boardx + 1] == 0)
{
board[boardy][boardx + 1] = tile;
board[boardy][boardx] = 0;
return true;
}
}
return false;
}
``````

I'm really not seeing where the problem is here. It seems to me that I did the same thing for x as I did for y. Yet, it doesn't seem to work.

If anybody can see the issue, I would greatly appreciate it.

• The code looks right to me. I'm thinking that the problem lies in what you didn't post. Something may be wrong in the setup, or who knows what else. This looks like part of a function called from main. Can you add the rest of the function? Feb 5 '16 at 19:08
• Ok, posting in a comment didn't work, I'll edit the above code :) Feb 5 '16 at 19:12

## 1 Answer

So, it was a subtle problem and an easy mistake to make. Look at the limits on your 4 conditions: > 0 and < d. >0 works because it allows for swapping to array elements with 0 as an index. However,

For example, say that d=3. Given `if (board[boardy][boardx + 1] == 0)` that means that in this case, if boardx = 2, then boardx+1=3, so you're trying to reference a cell outside of the array.

Change `<d` to `<d-1` and it should work fine.

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

• Ah, thank you very much! Feb 5 '16 at 20:18