#include #include #include #include #include "queue.h" #include "input.h" #define INPUT "input/05.txt" #define EXPECTED1 70369L #define EXPECTED2 203002L #define STACK_COUNT 9 SLIST_HEAD(crate_list, crate) head[STACK_COUNT]; struct crate { char crate_char; SLIST_ENTRY(crate) entries; }; struct crate* last_crate[STACK_COUNT]; void move_9001(int count, struct crate_list* from_head, struct crate* from_crate, struct crate_list* to_head) { // use a recursion to move the crates from bottom up if(count > 1) { move_9001(count - 1, from_head, SLIST_NEXT(from_crate, entries), to_head); } SLIST_REMOVE(from_head, from_crate, crate, entries); SLIST_INSERT_HEAD(to_head, from_crate, entries); } void move_crates(struct input_str* input, bool is_crane_9000) { // parse stacks 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--; if(is_crane_9000) 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); } else move_9001(crate_count, head + from, SLIST_FIRST(head + from), head + to); } // print result 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 } int main() { // read input struct input_str input; input_str_read(&input, INPUT); // do stuff move_crates(&input, true); // BSDMQFLSP expected move_crates(&input, false); // PGSQBFLDP expected // cleanup & exit input_str_free(&input); return 0; }