day 14 part twoq
authorMart Lubbers <mart@martlubbers.net>
Tue, 14 Dec 2021 09:52:48 +0000 (10:52 +0100)
committerMart Lubbers <mart@martlubbers.net>
Tue, 14 Dec 2021 09:52:48 +0000 (10:52 +0100)
14a.c
14b.c [new file with mode: 0644]

diff --git a/14a.c b/14a.c
index c97d360..7b52084 100644 (file)
--- a/14a.c
+++ b/14a.c
@@ -25,7 +25,7 @@ int main()
                HASH_ADD(hh, template, key, sizeof(struct pair), t);
        }
 
-       for (int i = 0; i<10; i++) {
+       for (int i = 0; i<20; i++) {
                free(oldinput);
                oldinput = input;
                input = malloc(inputlen *= 2);
diff --git a/14b.c b/14b.c
new file mode 100644 (file)
index 0000000..83ebab0
--- /dev/null
+++ b/14b.c
@@ -0,0 +1,65 @@
+#include <stdio.h>
+#include <stdbool.h>
+#include <limits.h>
+#include <string.h>
+
+#define lookup(i, x1, x2) (i)[((x1)-'A')+((x2)-'A')*26]
+
+int main()
+{
+       char *buf = NULL;
+       size_t len;
+       char template[26*26] = {0};
+       unsigned long input1[26*26] = {0};
+       unsigned long input2[26*26] = {0};
+       unsigned long *input = input1;
+       unsigned long *newinput = input2;
+
+       int first = getchar();
+       int c, oldc = first;
+       unsigned long freq[26] = {0};
+       while ( (c = getchar()) != '\n') {
+               lookup(input, oldc, c) = 1;
+               oldc = c;
+       }
+
+       while (getline(&buf, &len, stdin) != -1) {
+               if (buf[0] == '\n')
+                       continue;
+               lookup(template, buf[0], buf[1]) = buf[6];
+       }
+
+       for (int step = 0; step < 40; step++) {
+               for (char x = 'A'; x<='Z'; x++) {
+                       for (char y = 'A'; y<='Z'; y++) {
+                               char ins = lookup(template, x, y);
+                               if (ins != '\0') {
+                                       unsigned long freq = lookup(input, x, y);
+                                       lookup(newinput, x, ins) += freq;
+                                       lookup(newinput, ins, y) += freq;
+                               }
+                       }
+               }
+               unsigned long *t = newinput;
+               newinput = input;
+               input = t;
+               memset(&newinput[0], 0, sizeof(input1));
+       }
+
+       for (char x = 'A'; x<='Z'; x++) {
+               for (char y = 'A'; y<='Z'; y++) {
+                       freq[x-'A'] += lookup(input, x, y);
+                       freq[y-'A'] += lookup(input, x, y);
+               }
+       }
+       freq[first-'A']++;
+       freq[oldc-'A']++;
+
+       unsigned long min = ULONG_MAX, max = 0;
+       for (int i = 0; i<26; i++) {
+               max = freq[i] > max ? freq[i] : max;
+               min = freq[i] > 1 && freq[i] < min ? freq[i] : min;
+       }
+
+       printf("%lu\n", max/2-min/2);
+}