# pset3 not being able to swap valid move

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

if(tile>=(d*d)||d<0)
{
return false;
}

int space = board[d-1][d-1];
for(int i=0;i<d;i++)
{
for(int j=0;j<d;j++)
{
if(tile==board[i][j])
{
if(space==board[i][j-1])
{
board[i][j-1]=tile;
board[i][j]=space;
return true;
}
if(space==board[i][j+1])
{
board[i][j+1]=tile;
board[i][j]=space;
return true;
}
if(space==board[i-1][j])
{
board[i-1][j]=tile;
board[i][j]=space;
return true;
}
if(space==board[i+1][j])
{
board[i+1][j]=tile;
board[i][j]=space;
return true;
}
}

}

}
return false;
}
``````

help me debug this code for move function

## 1 Answer

This code has two serious problems. First, it initialized space as the lower right tile. This is only guaranteed to be true at the beginning of the game. After that, space will be defined as whatever value is in the lower right corner by `int space = board[d-1][d-1];`.

After this is dealt with, there's another problem. The swap code looks at data that is off the edge of the board. When i (or j) is allowed to go to d-1, the code looks for space at board[i+1][j]. This means that if i=d-1, then it's looking at board[d][j]. Similarly, if i=0, it looks at board[i-1][j], or board[-1][j]. Both of these are invalid. Same logic applies to j. Since c doesn't look at this as an error, garbage data gets swapped into the board array.

There may be other issues but this should get you going again. If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

• thanks.I have found issue of this code Oct 19, 2016 at 1:40