0

Thanks in advance for any tips. Why is my code generating lots of extra 000s when I generate the array? The code below outputs something like {{8,7,6,0,0,0,0,0,0},{5,4,3,0,0,0,0,0,} etc. This seems to print as expected.

876

543

21_

But doesn't work when it comes to move the tile. Here is my function used to generate the array, and below the move function.

for(int row = 0; row < d; row++){
    for(int col = 0; col < d; col++){
        if( size - count == 2 && d%2 == 0){
             board[row][col] = 1;
        }

        else if( size - count == 1 && d%2 == 0) {
             board[row][col] = 2;
        }
        else {
            board[row][col] = size - count;
        }
        count += 1;
    }
}

And to move the tile:

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

I realise the move function looks quite inelegant right now, I am sure it also needs to be refactored. Thanks in advance

1

Why is my code generating lots of extra 000s

The board is declared globally as

board[DIM_MAX][DIM_MAX]

where DIM_MAX is 9.

As such, you get a 9x9 array filled with zeros (all globally declared variables are initialized with 0).

1
  • Ok, that makes sense, thank you Oct 23 '17 at 10:58

You must log in to answer this question.

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