From 98c12e340a2b798aecc506821d61fa219fd5d238 Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Sat, 10 Dec 2022 15:04:52 +0000 Subject: Solve puzzle 10 part 2 --- 10.c | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/10.c b/10.c index a5e3d8e..033dcdd 100644 --- a/10.c +++ b/10.c @@ -2,18 +2,38 @@ #include #include #include +#include int -main() +main(int argc, char ** argv) { + int part = 1, cyclelimit = 220; 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) { + while ((cycle = getopt(argc, argv, "p:")) != -1) { + switch (cycle) { + case 'p': + part = atoi(optarg); + switch (part) { + case 1: cyclelimit = 220; break; + case 2: cyclelimit = 1000; break; + default: + fprintf(stderr, "Unexpected part: %d\n", part); + return -1; + } + break; + + default: + return -1; + } + } + + for (cycle = 1; cycle <= cyclelimit; ++cycle) { // Start of cycle. Do we need to read a new instruction? if (opcycles == 0) { char * toksave = NULL; @@ -39,11 +59,20 @@ main() } // Mid-cycle debugger attachment. - if (cycle >= nextread) { + if (part == 1 && cycle >= nextread) { total += rx * cycle; nextread += interval; } + // Mid-cycle CRT output. + if (part == 2) { + int pixel = (cycle - 1) % interval; + int insprite = pixel >= rx - 1 && pixel <= rx + 1; + fputc(insprite ? '#' : '.', stdout); + if (pixel == interval - 1) + fputc('\n', stdout); + } + // Perform cycle. Reduce opcycle count, do actions that occur on // op completion and increment cycle counter. --opcycles; @@ -55,7 +84,8 @@ main() } } - printf("Sum of interesting signal strengths: %d\n", total); + if (part == 1) + printf("Sum of interesting signal strengths: %d\n", total); return 0; } -- cgit v1.2.1