day 15 golfed m4, 829 effective bytes
[aoc_eblake.git] / 2016 / advent10.c
blob8d445dedeced15cd536715ccbf8ff176ef13ef25
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 // cheat by pre-inspecting: all values and bots between 0 and 255 exclusive
10 #define MAX 255
11 typedef struct bot bot;
12 struct bot {
13 unsigned char v1;
14 unsigned char v2;
15 unsigned char lo;
16 unsigned char hi;
17 bool out_lo;
18 bool out_hi;
19 bool done;
20 } bots[MAX];
21 unsigned char out[MAX];
23 int main(int argc, char **argv)
25 ssize_t nread;
26 size_t len = 0;
27 char *line = NULL;
28 int inputs = 0;
29 int tasks = 0;
30 while ((nread = getline(&line, &len, stdin)) >= 0) {
31 if (*line == 'v') {
32 int v, b;
33 inputs++;
34 if (sscanf (line, "value %d goes to bot %d\n", &v, &b) != 2)
35 return 1;
36 if (bots[b].v1)
37 bots[b].v2 = v;
38 else
39 bots[b].v1 = v;
40 } else {
41 int b0, b1, b2;
42 char t1, t2;
43 tasks++;
44 if (sscanf (line, "bot %d gives low to %c%*s %d and high to %c%*s %d\n",
45 &b0, &t1, &b1, &t2, &b2) != 5)
46 return 1;
47 if (t1 == 'o')
48 bots[b0].out_lo = true;
49 if (t2 == 'o')
50 bots[b0].out_hi = true;
51 bots[b0].lo = b1;
52 bots[b0].hi = b2;
55 printf ("%d inputs are sorted among %d bots\n", inputs, tasks);
56 bool change = true;
57 int goal = 0;
58 int iter = 0;
59 while (change) {
60 printf (" iteration %d\n", iter++);
61 change = false;
62 for (int i = 0; i < MAX; i++)
63 if (!bots[i].done && bots[i].v1 && bots[i].v2) {
64 printf ("tracing bot %d, v1 %d, v2 %d, lo %d, hi %d\n",
65 i, bots[i].v1, bots[i].v2, bots[i].lo, bots[i].hi);
66 bots[i].done = change = true;
67 if (bots[i].v1 > bots[i].v2) {
68 unsigned char tmp = bots[i].v1;
69 bots[i].v1 = bots[i].v2;
70 bots[i].v2 = tmp;
72 unsigned char *l, *h;
73 if (bots[i].out_lo)
74 l = &out[bots[i].lo];
75 else if (bots[bots[i].lo].v1)
76 l = &bots[bots[i].lo].v2;
77 else
78 l = &bots[bots[i].lo].v1;
79 if (bots[i].out_hi)
80 h = &out[bots[i].hi];
81 else if (bots[bots[i].hi].v1)
82 h = &bots[bots[i].hi].v2;
83 else
84 h = &bots[bots[i].hi].v1;
85 *l = bots[i].v1;
86 *h = bots[i].v2;
87 if (bots[i].v1 == 17 && bots[i].v2 == 61)
88 goal = i;
91 printf ("values 17 and 61 are compared by bot %d\n", goal);
92 printf ("first three outputs have product %d\n", out[0] * out[1] * out[2]);
93 return 0;