0

Why does my code to swap tiles give the value zero to board[d-1][d-3] and board[d-1][d-2]?

printf("give me\n");
int d = GetInt();

int board[d][d];
int k = d*d-1;

for(int i = 0; i < d; i++)
{
    for (int j = 0; j < d; ++j)
    {
        board[i][j] = k;
        int t = board[d-1][d-2];
        board[d-1][d-2] = board[d-1][d-3];
        board[d-1][d-3] = t;
        printf(" %2i ", board[i][j]);
        --k;
    }     
        printf("\n");
    } 
}
1
  • Please @pavlosromios try to format your code properly when posting it here to be peer-reviewed. Previewing your question prior to actually "posting" can be really helpful in order to do that :)
    – abelinux
    Commented Dec 27, 2014 at 13:33

1 Answer 1

1

When you do:

for(int i = 0; i < d; i++)
{
    for (int j = 0; j < d; ++j)
    {
        ...
        /* Swapping ALWAYS the same tiles, since 'd' is a fixed value */
        int t = board[d-1][d-2];
        board[d-1][d-2] = board[d-1][d-3];
        board[d-1][d-3] = t;
        ...
    }     
        printf("\n");
    } 
}

The general idea is close to right (for the "swapping tiles" algorithm): grabbing a certain tile, store it in a temp value, and then swap two contiguous values. The problem is that, never mind the for loop, you're always accesing the same positions in the board[][] array, because you're accesing it with d, which is a fixed value.

Besides, you're actually performing these two steps within the same loop:

  • Filling the board with tiles
  • Swapping values to be moved

Of course, first times through the loop you're trying to swap values that have not been initialized yet. Luckily enough, you get zero, but in theory you could get any value at all (remember those ? in the lectures?)

You should consider splitting those steps in two different functions, like:

  • init_board()
  • move()

I.e.: your board should be entirely initialized before your first attempt to move a tile.

Perhaps you should start by laying out your algorithm in pseudocode, and better understand how the program will work, and only then translate that to actual 'C' code.

2
  • thanks.i should have out it out of the loop Commented Dec 27, 2014 at 15:10
  • if this answer is useful and actually answers your question, please mark it so (using the "accept answer" button) for future students to benefit from an already answered question.
    – abelinux
    Commented Dec 27, 2014 at 15:51

You must log in to answer this question.

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