From 42d89de7320a95ee4d689f03ab571b8cf95e25a4 Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Sat, 10 Dec 2022 13:14:28 +0000 Subject: Solve puzzle 10 part 1 --- 10.c | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 10.c (limited to '10.c') diff --git a/10.c b/10.c new file mode 100644 index 0000000..a5e3d8e --- /dev/null +++ b/10.c @@ -0,0 +1,62 @@ + +#include +#include +#include + + +int +main() +{ + int cycle; + char buf[BUFSIZ]; + char * op, * arg; + int opcycles = 0; + int rx = 1, nextread = 20, interval = 40, total = 0; + + for (cycle = 1; cycle <= 220; ++cycle) { + // Start of cycle. Do we need to read a new instruction? + if (opcycles == 0) { + char * toksave = NULL; + + if (!fgets(buf, sizeof(buf), stdin)) + break; + + op = strtok_r(buf, " \n", &toksave); + arg = strtok_r(NULL, "\n", &toksave); + + // Just read instruction. Set op cycle count, and + // perform any immediate actions + if (strcmp(op, "noop") == 0 && !arg) { + opcycles = 1; + } + else if (strcmp(op, "addx") == 0 && arg) { + opcycles = 2; + } + else { + fprintf(stderr, "Unexpected op/arg: %s/%s\n", op, arg ? arg : "(null)"); + return -1; + } + } + + // Mid-cycle debugger attachment. + if (cycle >= nextread) { + total += rx * cycle; + nextread += interval; + } + + // Perform cycle. Reduce opcycle count, do actions that occur on + // op completion and increment cycle counter. + --opcycles; + + if (opcycles == 0) { + if (strcmp(op, "addx") == 0) { + rx += atoi(arg); + } + } + } + + printf("Sum of interesting signal strengths: %d\n", total); + + return 0; +} + -- cgit v1.2.1