7b52084a5617bc5bbce6fd3a77eeb190c1b14990
[advent21.git] / 14a.c
1 #include <stdio.h>
2 #include <stdbool.h>
3 #include <limits.h>
4
5 #include <uthash.h>
6
7 struct pair { char x; char y; };
8 struct template { struct pair key; char ins; UT_hash_handle hh; };
9
10 int main()
11 {
12 char *input = NULL, *buf = NULL, *oldinput = NULL;
13 size_t inputlen = 0, len;
14 struct template *template = NULL;
15
16 if (getline(&input, &inputlen, stdin) == -1)
17 return 1;
18 while (getline(&buf, &len, stdin) != -1) {
19 if (strcmp(buf, "\n") == 0)
20 continue;
21 struct template *t = calloc(1, sizeof(struct template));
22 t->key.x = buf[0];
23 t->key.y = buf[1];
24 t->ins = buf[6];
25 HASH_ADD(hh, template, key, sizeof(struct pair), t);
26 }
27
28 for (int i = 0; i<20; i++) {
29 free(oldinput);
30 oldinput = input;
31 input = malloc(inputlen *= 2);
32 inputlen = 0;
33 char *c;
34 for (c = &oldinput[0]; *c != '\0'; c++) {
35 input[inputlen++] = *c;
36 struct pair p = {.x=c[0], .y=c[1]};
37 struct template *t;
38 HASH_FIND(hh, template, &p, sizeof(struct pair), t);
39 if (t)
40 input[inputlen++] = t->ins;
41 }
42 input[inputlen++] = '\0';
43 }
44
45 int freq[255] = {0};
46 int mcommon = 0, lcommon = INT_MAX;
47 for (char *c = &input[0]; *c != '\0'; *c++) {
48 freq[*c]++;
49 }
50 for (int i = 0; i<255; i++) {
51 if (freq[i] > mcommon)
52 mcommon = freq[i];
53 if (freq[i] > 1 && freq[i] < lcommon)
54 lcommon = freq[i];
55 }
56
57 printf("%d\n", mcommon-lcommon);
58 }