aboutsummaryrefslogtreecommitdiff
path: root/advent-of-code/2022/05/2.c
blob: 8a3215d99ed71a3f607d428c2023d42fbb4f8335 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
#include <stdlib.h>

struct listnode {
    struct listnode *next;
    char val;
};
typedef struct {
    struct listnode *head;
} Stack;

void stack_push(Stack *s, char val) {
    struct listnode *n = malloc(sizeof(struct listnode));
    n->next = s->head;
    n->val = val;
    s->head = n;
}

char* stack_top(Stack *s) {
    if (s->head == NULL) return NULL;
    return &(s->head->val);
}

void stack_pop(Stack *s) {
    if (s->head == NULL) return;
    struct listnode *next = s->head->next;
    free(s->head);
    s->head = next;
}

char buf[4096];

int main() {
    Stack s[9];
    FILE *fp = fopen("input", "r");
    fread(buf, 1, 36 * 8, fp);
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 8; j++) {
            char c = buf[(7 - j) * 36 + i * 4 + 1];
            if (c != ' ') {
                stack_push(&s[i], c);
            }
        }
    }
    fgets(buf, 4096, fp);
    fgets(buf, 4096, fp);
    int amount, from, to;
    while (fscanf(fp, "move %d from %d to %d\n", &amount, &from, &to) > 0) {
        for (int i = 0; i < amount; i++) {
            char c = *stack_top(&s[from - 1]);
            stack_pop(&s[from - 1]);
            buf[i] = c;
        }
        for (int i = 0; i < amount; i++) {
            int n = amount - i - 1;
            stack_push(&s[to-1], buf[n]);
        }
    }
    for (int i = 0; i < 9; i++) {
        printf("%c", *stack_top(&s[i]));
    }
    printf("\n");
    return 0;
}