day 16 part 2 solved
[aoc_eblake.git] / 2016 / advent12.c
blob80a359af4b930be983e9cb8a98b3184b8c0f8fbb
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 regs[*reg - 'a'] = value;
26 int main(int argc, char **argv)
28 int instr = 0;
29 char buf[200]; // sized based on pre-inspecting file
30 int nread = fread (buf, 1, sizeof buf, stdin);
31 char *p = buf;
32 while (p < buf + nread) {
33 program[instr++] = p;
34 p = strchr (p, '\n');
35 *p++ = '\0';
37 printf ("program consists of %d instructions\n", instr);
38 unsigned int pc = 0;
39 regs[2] = 1;
40 int count = 0;
41 while (pc < instr) {
42 char arg1[10], arg2[10];
43 count++;
44 sscanf (program[pc], "%*s %9s %9s", arg1, arg2);
45 switch (program[pc][0]) {
46 case 'c': // cpy
47 set (arg2, get (arg1));
48 pc++;
49 break;
50 case 'i': // inc
51 set (arg1, get (arg1) + 1);
52 pc++;
53 break;
54 case 'd': // dec
55 set (arg1, get (arg1) - 1);
56 pc++;
57 break;
58 case 'j': // jnz
59 if (get (arg1))
60 pc += atoi (arg2);
61 else
62 pc++;
63 break;
64 default:
65 return 1;
68 printf ("after %d operations, final content of register a: %d\n",
69 count, regs[0]);
70 return 0;