day 19 part 2 solved
[aoc_eblake.git] / 2016 / advent23.c
blob363020c343cefb90ebae4c436a19bf8926323f2c
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <stdbool.h>
7 #include <ctype.h>
9 int regs[4];
10 char *program[50]; // sized based on pre-inspecting file
12 int
13 get (const char *value)
15 if (isalpha(*value))
16 return regs[*value - 'a'];
17 return atoi (value);
20 void
21 set (const char *reg, int value)
23 if (getenv ("DEBUG"))
24 printf (" setting %s to %d\n", reg, value);
25 regs[*reg - 'a'] = value;
28 int main(int argc, char **argv)
30 int instr = 0;
31 char buf[200]; // sized based on pre-inspecting file
32 int nread = fread (buf, 1, sizeof buf, stdin);
33 char *p = buf;
34 while (p < buf + nread) {
35 program[instr++] = p;
36 p = strchr (p, '\n');
37 *p++ = '\0';
39 printf ("program consists of %d instructions\n", instr);
40 unsigned int pc = 0;
41 regs[0] = 12;
42 long long count = 0;
43 while (pc < instr) {
44 char arg1[10], arg2[10];
45 unsigned int line;
46 count++;
47 if (getenv ("DEBUG"))
48 printf ("count=%lld pc=%d a=%d b=%d c=%d d=%d, executing %s\n", count,
49 pc, regs[0], regs[1], regs[2], regs[3], program[pc]);
50 sscanf (program[pc], "%*s %9s %9s", arg1, arg2);
51 switch (program[pc][0]) {
52 case 'c': // cpy x y
53 if (isalpha (*arg2))
54 set (arg2, get (arg1));
55 break;
56 case 'i': // inc x
57 set (arg1, get (arg1) + 1);
58 break;
59 case 'd': // dec x
60 set (arg1, get (arg1) - 1);
61 break;
62 case 'j': // jnz x y
63 if (get (arg1))
64 pc += get (arg2) - 1;
65 break;
66 case 't': // tgl x
67 line = get (arg1) + pc;
68 if (line < instr) {
69 if (getenv ("DEBUG"))
70 printf (" rewriting instruction %d, was %s\n", line, program[line]);
71 switch (*program[line]) {
72 case 'i':
73 memcpy (program[line], "dec", 3);
74 break;
75 case 'd':
76 case 't':
77 memcpy (program[line], "inc", 3);
78 break;
79 case 'c':
80 memcpy (program[line], "jnz", 3);
81 break;
82 case 'j':
83 memcpy (program[line], "cpy", 3);
84 break;
85 default:
86 return 1;
89 break;
90 default:
91 return 1;
93 pc++;
95 printf ("after %lld operations, final content of register a: %d\n",
96 count, regs[0]);
97 return 0;