diff options
author | Adam Spragg <adam@spra.gg> | 2022-12-10 13:14:28 +0000 |
---|---|---|
committer | Adam Spragg <adam@spra.gg> | 2022-12-10 13:14:28 +0000 |
commit | 42d89de7320a95ee4d689f03ab571b8cf95e25a4 (patch) | |
tree | d1662c3565c780cb279bc68dfde92369d3bea191 | |
parent | 4bd1be7ccd2179436c9b55cc76f348282e7af15d (diff) |
Solve puzzle 10 part 1
-rw-r--r-- | 10.c | 62 | ||||
-rw-r--r-- | makefile | 1 |
2 files changed, 63 insertions, 0 deletions
@@ -0,0 +1,62 @@ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + + +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; +} + @@ -11,6 +11,7 @@ all: bin \ bin/7 \ bin/8 \ bin/9 \ + bin/10 \ bin: mkdir -p $@ |