part one day 14
[advent21.git] / 14a.c
diff --git a/14a.c b/14a.c
new file mode 100644 (file)
index 0000000..c97d360
--- /dev/null
+++ b/14a.c
@@ -0,0 +1,58 @@
+#include <stdio.h>
+#include <stdbool.h>
+#include <limits.h>
+
+#include <uthash.h>
+
+struct pair { char x; char y; };
+struct template { struct pair key; char ins; UT_hash_handle hh; };
+
+int main()
+{
+       char *input = NULL, *buf = NULL, *oldinput = NULL;
+       size_t inputlen = 0, len;
+       struct template *template = NULL;
+
+       if (getline(&input, &inputlen, stdin) == -1)
+               return 1;
+       while (getline(&buf, &len, stdin) != -1) {
+               if (strcmp(buf, "\n") == 0)
+                       continue;
+               struct template *t = calloc(1, sizeof(struct template));
+               t->key.x = buf[0];
+               t->key.y = buf[1];
+               t->ins = buf[6];
+               HASH_ADD(hh, template, key, sizeof(struct pair), t);
+       }
+
+       for (int i = 0; i<10; i++) {
+               free(oldinput);
+               oldinput = input;
+               input = malloc(inputlen *= 2);
+               inputlen = 0;
+               char *c;
+               for (c = &oldinput[0]; *c != '\0'; c++) {
+                       input[inputlen++] = *c;
+                       struct pair p = {.x=c[0], .y=c[1]};
+                       struct template *t;
+                       HASH_FIND(hh, template, &p, sizeof(struct pair), t);
+                       if (t)
+                               input[inputlen++] = t->ins;
+               }
+               input[inputlen++] = '\0';
+       }
+
+       int freq[255] = {0};
+       int mcommon = 0, lcommon = INT_MAX;
+       for (char *c = &input[0]; *c != '\0'; *c++) {
+               freq[*c]++;
+       }
+       for (int i = 0; i<255; i++) {
+               if (freq[i] > mcommon)
+                       mcommon = freq[i];
+               if (freq[i] > 1 && freq[i] < lcommon)
+                       lcommon = freq[i];
+       }
+
+       printf("%d\n", mcommon-lcommon);
+}