From 9f57e15a054b16d335e9d5c49ddd7be829b4e272 Mon Sep 17 00:00:00 2001 From: kartofen Date: Sat, 10 Dec 2022 10:37:32 +0200 Subject: day 10 --- Advent-of-Code-2022/aoc-10/main.c | 86 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Advent-of-Code-2022/aoc-10/main.c (limited to 'Advent-of-Code-2022/aoc-10/main.c') diff --git a/Advent-of-Code-2022/aoc-10/main.c b/Advent-of-Code-2022/aoc-10/main.c new file mode 100644 index 0000000..526d5d0 --- /dev/null +++ b/Advent-of-Code-2022/aoc-10/main.c @@ -0,0 +1,86 @@ +#include +#include +#include +#include + +#if 0 + #define PART part1 +#else + #define PART part2 +#endif + +#if 0 + #define FILENAME "sample.txt" +#else + #define FILENAME "input.txt" +#endif + +#define CMDS 2 +char commands[CMDS][5] = {"noop", "addx"}; +char cmdcycles[CMDS] = {1, 2}; + +int x = 1; +int cycles = 0; +int sum = 0; + +void part1() +{ + cycles++; + + if((cycles+20) % 40 == 0) sum += cycles * x; +} + +void part2() +{ + int i = cycles % 40; + printf("%c", (x == i || x == i+1 || x == i-1) ? '#' : '.'); + if(i == 39) printf("\n"); + + cycles++; +} + +int parse_cmd(char *cmdstr) +{ + for(int i = 0; i < CMDS; i++) + if(strncmp(commands[i], cmdstr, 4) == 0) return i; + return -1; +} + +void parse() +{ + FILE *fp = fopen(FILENAME, "r"); + if(!fp) { + fprintf(stderr, "ERROR: Could not open file: %s\n", FILENAME); + exit(1); + } + + char line[256]; + while(fgets(line, sizeof(line), fp)) + { + int cmd = parse_cmd(strtok(line, " ")); + assert(cmd >= 0); + + for(int i = 0; i < cmdcycles[cmd]; i++) + { + PART(); + + switch(cmd) { + case 0: + break; + case 1: + if(i == 1) x += atoi(strtok(NULL, " ")); + break; + } + + } + } + + fclose(fp); +} + +int main(void) +{ + parse(); + printf("%d\n", sum); + return 0; +} -- cgit v1.2.3