From 869259ef4e4ad3d3c77763436d004c2dc7db1fb7 Mon Sep 17 00:00:00 2001 From: Rokas Puzonas Date: Sun, 11 Dec 2022 02:59:49 +0200 Subject: [PATCH] solve day 10 --- day10.c | 126 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ main.c | 1 + 2 files changed, 127 insertions(+) create mode 100644 day10.c diff --git a/day10.c b/day10.c new file mode 100644 index 0000000..2c497e5 --- /dev/null +++ b/day10.c @@ -0,0 +1,126 @@ +#include +#include +#include +#include + +#include "aoc.h" + +typedef enum { + INST_TYPE_NOOP, + INST_TYPE_ADD, +} INST_TYPE; + +typedef struct { + INST_TYPE type; + int amount; +} Instruction; + +typedef struct { + Instruction *instructions; + int count; +} day10_Data; + +static void *day10_parse(char **lines, int line_count) +{ + day10_Data *data = malloc(sizeof(day10_Data)); + data->count = line_count; + data->instructions = malloc(line_count * sizeof(Instruction)); + + for (int i = 0; i < line_count; i++) { + char *line = lines[i]; + Instruction *inst = &data->instructions[i]; + if (!strcmp(line, "noop")) { + inst->type = INST_TYPE_NOOP; + } else { // addx + inst->type = INST_TYPE_ADD; + inst->amount = atoi(line + 5); + } + } + + return data; +} + +static void day10_part1(void *p) +{ + day10_Data *data = p; + + int regx = 1; + int result = 0; + int inst_idx = 0; + int cycle = 0; + int add_timer = 0; + bool add_started = false; + while (inst_idx < data->count) { + Instruction *inst = &data->instructions[inst_idx]; + if (!add_started) { + if (inst->type == INST_TYPE_NOOP) { + inst_idx++; + } else if (inst->type == INST_TYPE_ADD) { + add_started = true; + add_timer = 2; + } + } + + cycle++; + + if ((cycle - 20) % 40 == 0 && cycle <= 220) { + result += cycle*regx; + } + + if (add_started) { + add_timer--; + if (add_timer == 0) { + add_started = false; + regx += inst->amount; + inst_idx++; + } + } + } + + printf("%d\n", result); +} + +static void day10_part2(void *p) +{ + day10_Data *data = p; + + int regx = 1; + int inst_idx = 0; + int cycle = 0; + int add_timer = 0; + bool add_started = false; + while (inst_idx < data->count) { + Instruction *inst = &data->instructions[inst_idx]; + if (!add_started) { + if (inst->type == INST_TYPE_NOOP) { + inst_idx++; + } else if (inst->type == INST_TYPE_ADD) { + add_started = true; + add_timer = 2; + } + } + + if (abs(cycle % 40 - regx) <= 1) { + printf("#"); + } else { + printf("."); + } + + cycle++; + + if (add_started) { + add_timer--; + if (add_timer == 0) { + add_started = false; + regx += inst->amount; + inst_idx++; + } + } + + if (cycle % 40 == 0) { + printf("\n"); + } + } +} + +ADD_SOLUTION(10, day10_parse, day10_part1, day10_part2); diff --git a/main.c b/main.c index 50dcf84..f97e1dd 100644 --- a/main.c +++ b/main.c @@ -17,6 +17,7 @@ #include "day7.c" #include "day8.c" #include "day9.c" +#include "day10.c" Solution *find_solution(int day) {