0

So, I can locate the blank tile and the called number to swap, swap them (although through a number of steps), and then print the new board. The problem arises when I move the largest number. The program can move the number once, but after that, it still thinks the largest number stayed in place. So, a number can skip over the largest number, resulting into this:

enter image description here ..my code for move is

bool move(int tile){
int tempX = 0;
int tempY = 0;
int tileX = 0;
int tileY = 0;
if (tile < ((d*d)-1) && tile > 0){
    for(int i = 0;i < d;i++){
        for (int j = 0;j < d;j++){
            if(tile == board[i][j]){
                //locate the tile
                tileX = i;
                tileY = j;
            }
        }
    }    
}
//checks if the number called is next to the blank
if(board[blankX][blankY] == board[tileX+1][tileY] || board[blankX][blankY] == board[tileX-1][tileY] || board[blankX][blankY] == board[tileX][tileY-1]|| board[blankX][blankY] == board[tileX][tileY+1]){
    //swaps the number called with blank
    tempX = blankX;
    tempY = blankY; 
    board[blankX][blankY] = board[tileX][tileY];
    blankX = tileX; 
    blankY = tileY;
    board[tileX][tileY] = 0; 
    tileY = tempY;
    tileX = tempX;
    return true;
}

else{
    return false;
}

}

Can the error be in the 0? Should I rewrite the whole swap function? It's the only one that worked so far.

1
  • Noticed another bug in your code, which is not really an answer to your question -- but think what happens when your first if statement (if (tile < ((d*d)-1) && tile > 0)) fails?... the second part your code still gets executed...
    – Hedgehog
    Oct 26 '14 at 19:44
1

I doesn't really skip over 8 as such. It simply swaps the 6 and the _, because it thinks they are adjacent.

The last move you entered was 6. Your program should have given an error, as 6 and _ are not actually adjacent.

You logic in:

if(board[blankX][blankY] == board[tileX+1][tileY] || board[blankX][blankY] == board[tileX-1][tileY] || board[blankX][blankY] == board[tileX][tileY-1]|| board[blankX][blankY] == board[tileX][tileY+1]){

is slightly "flawed". Not really "flawed," but incomplete. Let's take a tile in the top right corner of the board, ie tileX = 2 and tileY = 0.

What happens when you access board[tileX+1][tileY]? (Hint: it's outside of the range of the array.)

Because of the way 2D arrays are laid out in C, it ends up overlapping and thinks that 6 and _ are adjacent.

You must log in to answer this question.

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