#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; }