0

Please explain me why fifteen's move() function is successfully compiles and, runs but keeps printing "Tile to move:" without printing anything else like invalid input and so on. GDB gives me the correct output, but I can't play game.

  • Removed code, public posting of solution code (working or not) is a no no: "Providing or making available solutions to problem sets to individuals who might take this course in the future. – Sean DiSanti Jun 18 '14 at 7:07
2

It looks like you have some repeated code. If you try to separate your move function into conceptually different parts, your issues will probably become much more clear. For example:

Part 1: Find where tile is Part 2: Check if tile is close to the 0 Part 3: Swap them if valid and return

This way you can use printfs to determine which of the parts contains your bug.

Also make sure to check if, say, j-1 >= 0 before doing board[i][j-1], for otherwise you are trying to access an invalid array value.

| improve this answer | |
0

Some comments to your code would make things way easier for us! :)

First, what do you think j - 1 in board[i][j - 1] will be evaluated to in case of j = 0 (at the first iteration of the nested for loop)?

Second, the blank tile should be a constant value because it doesn't change ever! And this will make the swapping process very easy. For example, I may define BLANK as -1

#define BLANK -1

then when it comes to the swapping process, it becomes as easy as this:

Assuming that row and column are the row and the column of the tile to be moved and blankRow and blankColumn are the row and the column of the blank tile respectively,

board[blankRow][blankColumn] = board[row][column];
board[row][column] = BLANK;

you may also rethink about the process of checking the adjacent tiles to see whether the blank tile is one of them.

And lastly, you may consider this pseudocode

// search for the tile
declare a boolean named found and set it to false
declare an int named row
declare an int named column

for (row = 0 to row < d AND found is not true, increase row)
{
    for (column = 0 to column < d, increase column)
    {
        if (board[row][column] == tile)
        {
            set found to true
            break;
        }
    }
}

// up
if (row > 0)
{
    if (board[row - 1][column] is the blank tile)
    {
        make the move
        return true
    }
}

// right
if (column < d - 1)
{
    if (board[row][column + 1] is the blank tile)
    {
        make the move
        return true     
    }    
}

// bottom
if (row < d - 1)
{
    if (board[row + 1][column] is the blank tile)
    {
        make the move
        return true
    }
}

// left
if (column > 0)
{
    if (board[row][column - 1] is the blank tile)
    {
        make the move
        return true
    }
}

return false
| improve this answer | |

You must log in to answer this question.

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