day 14 part twoq
[advent21.git] / 14b.c
1 #include <stdio.h>
2 #include <stdbool.h>
3 #include <limits.h>
4 #include <string.h>
5
6 #define lookup(i, x1, x2) (i)[((x1)-'A')+((x2)-'A')*26]
7
8 int main()
9 {
10 char *buf = NULL;
11 size_t len;
12 char template[26*26] = {0};
13 unsigned long input1[26*26] = {0};
14 unsigned long input2[26*26] = {0};
15 unsigned long *input = input1;
16 unsigned long *newinput = input2;
17
18 int first = getchar();
19 int c, oldc = first;
20 unsigned long freq[26] = {0};
21 while ( (c = getchar()) != '\n') {
22 lookup(input, oldc, c) = 1;
23 oldc = c;
24 }
25
26 while (getline(&buf, &len, stdin) != -1) {
27 if (buf[0] == '\n')
28 continue;
29 lookup(template, buf[0], buf[1]) = buf[6];
30 }
31
32 for (int step = 0; step < 40; step++) {
33 for (char x = 'A'; x<='Z'; x++) {
34 for (char y = 'A'; y<='Z'; y++) {
35 char ins = lookup(template, x, y);
36 if (ins != '\0') {
37 unsigned long freq = lookup(input, x, y);
38 lookup(newinput, x, ins) += freq;
39 lookup(newinput, ins, y) += freq;
40 }
41 }
42 }
43 unsigned long *t = newinput;
44 newinput = input;
45 input = t;
46 memset(&newinput[0], 0, sizeof(input1));
47 }
48
49 for (char x = 'A'; x<='Z'; x++) {
50 for (char y = 'A'; y<='Z'; y++) {
51 freq[x-'A'] += lookup(input, x, y);
52 freq[y-'A'] += lookup(input, x, y);
53 }
54 }
55 freq[first-'A']++;
56 freq[oldc-'A']++;
57
58 unsigned long min = ULONG_MAX, max = 0;
59 for (int i = 0; i<26; i++) {
60 max = freq[i] > max ? freq[i] : max;
61 min = freq[i] > 1 && freq[i] < min ? freq[i] : min;
62 }
63
64 printf("%lu\n", max/2-min/2);
65 }