10295 - I2P homework9   

Description

The game of 2048 is very simple. Given a 4x4 map containing tiles and spaces. The values are displayed on the tiles, and the spaces are displayed as 0. The values of tiles are always the power of 2. For example,
    2    2   64  128
    4    0    4   16
    4    4    4    4
    0    0    2    0

is a valid map.

We are able to slide the tiles in 4 directions(right, down, left and up). The rules of sliding is defined as follows:
1. All tiles slide past spaces. If you move the puzzle to the left, all spaces will end up on the right.
2. After sliding to collapse spaces, any tiles with the same value combine and the remainder of the row or column slides to fill in the hole.
3. One tile can only combine(be combined) once.
4. The combination always starts from the side of the direction. For example, after sliding left of 2, 2, 2, 0, it should be 4, 2, 0, 0.
5. Contrary to the famous game of 2048, there are no new tiles generated.

The direction is represented by a digit d(0 = right, 1 = down, 2 = left, 3 = up). So for instance if we have the map above and d = 2, after we slide the tiles, the map becomes
    4   64  128    0
    8   16    0    0
    8    8    0    0
    2    0    0    0


Your job is to slide the tiles correctly given a map and a sequence of directions.
Hint:

#include <stdio.h>

#define WIDTH 4
#define HEIGHT 4

int map[HEIGHT][WIDTH];

void collapse(int dir){
    /* your code here */
}

void slide(int dir){
    /* your code here */
}

void show(){
    int i, j;
    for(i = 0; i < HEIGHT; i++){
        for(j = 0; j < WIDTH; j++){
            printf(" %4d", map[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    int N, d;
    int i, j;

    scanf("%d", &N);
    for(i = 0; i < HEIGHT; i++){
        for(j = 0; j < WIDTH; j++){
            scanf("%d", &map[i][j]);
        }
    }

    for(i = 0; i < N; i++){
        scanf("%d", &d);
        slide(d);
    }

    show();

    return 0;
}

Input

N(the count of slides)
The map
The sliding sequence
 

Output

The final map
Note that the value of tiles will not exceed 8192.
 

Sample Input  Download

Sample Output  Download

Tags




Discuss