summaryrefslogtreecommitdiff
path: root/10.c
diff options
context:
space:
mode:
authorAdam Spragg <adam@spra.gg>2022-12-10 13:14:28 +0000
committerAdam Spragg <adam@spra.gg>2022-12-10 13:14:28 +0000
commit42d89de7320a95ee4d689f03ab571b8cf95e25a4 (patch)
treed1662c3565c780cb279bc68dfde92369d3bea191 /10.c
parent4bd1be7ccd2179436c9b55cc76f348282e7af15d (diff)
Solve puzzle 10 part 1
Diffstat (limited to '10.c')
-rw-r--r--10.c62
1 files changed, 62 insertions, 0 deletions
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 <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;
+}
+