0

So I've written the code for two of the functions in "fifteen", but after I compiled and started the program it prints a bunch of zeros. I'm hoping for a tip from you guys. The code for the two functions:

/**
 * Initializes the game's board with tiles numbered 1 through d*d - 1
 * (i.e., fills 2D array with values but does not actually print them).  
 */
void init(void)
{
    for(int i = 0; i < d; i++)
    {
        int k = i + 1;
        for(int j = 0; j < d; j++)
        {
            board[i][j] = d * d - (k *(j + k));
        }
    }

    if(d == 4 || d == 6 || d == 8)
    {
        int swap = board[d - 1][d - 2];
        board[d - 1][d - 3] = board[d - 1][d - 2];
        board[d - 1][d - 3] = swap;
    }
}

/**
 * Prints the board in its current state.
 */
void draw(void)
{
    for(int i = 0; i < d; i++)
    {
        for(int j = 0; j < d; j++)
        {
            if(i == d - 1 && j == d - 1)
            {
               printf("%d", board[i][j] - 2);
            }
            else
            {
                printf("%2d", board[i][j]);
                printf(" ");
            }
        }
        printf("\n");
    }
}
1
 8  7  6  5  3  1  0 -3 -6

It is what makes init () when d3, just have to take pen and paper and do some calculations.

for(int i = 0; i < d; i++)
    {
        int k = i + 1;

it leads to a wrong result.

We start with a control variable before for loop, that contains the desired value when the loop (i = 0, j = 0) starts this value can be k = d*d-1

Like you do in your program assign the value k to board, decreased k.

if(d == 4 || d == 6 || d == 8)

can be summarized in if (d% 2 == 0)

You must log in to answer this question.

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