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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "queue.h"
#include "input.h"
#define INPUT "input/05.txt"
#define EXPECTED1 70369L
#define EXPECTED2 203002L
#define STACK_COUNT 9
void part1(struct input_str* input) {
// parse stacks
SLIST_HEAD(crate_list, crate) head[STACK_COUNT];
struct crate {
char crate_char;
SLIST_ENTRY(crate) entries;
};
struct crate* last_crate[STACK_COUNT];
for(int i = 0; i < STACK_COUNT; i++) {
SLIST_INIT(head + i);
last_crate[i] = SLIST_FIRST(head + i);
}
size_t line_index = 0;
while(input->lines[line_index][0] != '\n' && line_index < input->line_count) {
for(int s = 0; s < STACK_COUNT; s++) {
int stack_index = 1 + 4 * s;
char crate_char = input->lines[line_index][stack_index];
if(crate_char == ' ') // stack is empty here
continue;
struct crate* crate = malloc(sizeof(struct crate));
crate->crate_char = crate_char;
if(SLIST_EMPTY(head + s))
SLIST_INSERT_HEAD(head + s, crate, entries);
else
SLIST_INSERT_AFTER(last_crate[s], crate, entries);
last_crate[s] = crate;
}
line_index++;
}
line_index++;
// parse and execute crate movements
for(size_t i = line_index; i < input->line_count; i++) {
// parse, as usual copy line before strtok
char* line = copy_line(input->lines[i]);
//printf("%s\n", line);
char* number = strtok(line, " "); // move
//printf("%s\n", number);
number = strtok(NULL, " ");
int crate_count = atoi(number);
strtok(NULL, " "); // from
number = strtok(NULL, " ");
int from = atoi(number);
strtok(NULL, " "); // to
number = strtok(NULL, " ");
int to = atoi(number);
free(line);
// now execute
//printf("move %d from %d to %d\n", crate_count, from, to);
from--;
to--;
for(int m = 0; m < crate_count; m++) {
struct crate* cc = SLIST_FIRST(head + from);
SLIST_REMOVE_HEAD(head + from, entries);
SLIST_INSERT_HEAD(head + to, cc, entries);
}
}
// print result, expected is BSDMQFLSP with my input
for(int s = 0; s < STACK_COUNT; s++) {
struct crate* cc = SLIST_FIRST(head + s);
printf("%c", cc->crate_char);
}
printf("\n");
// TODO free all the crates
}
void part2(struct input_str* input) {
}
int main() {
// read input
struct input_str input;
input_str_read(&input, INPUT);
// do stuff
part1(&input);
part2(&input);
// cleanup & exit
input_str_free(&input);
return 0;
}
|