diff options
author | Vincent Douillet <vincent@vdouillet.fr> | 2022-12-06 22:54:39 +0100 |
---|---|---|
committer | Vincent Douillet <vincent@vdouillet.fr> | 2022-12-06 22:54:39 +0100 |
commit | 2490e48c629cc02af93f5fb685803a00725e3037 (patch) | |
tree | 22e3d43337ff459e8be17dfe1cbafbaf5af826c9 /05.c | |
parent | 47fd551daab476421411749c5806b3c213cf0a70 (diff) |
day 5 part 1
Diffstat (limited to '05.c')
-rw-r--r-- | 05.c | 98 |
1 files changed, 98 insertions, 0 deletions
@@ -0,0 +1,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; +} |