cleanup
[advent21.git] / 06b.c
diff --git a/06b.c b/06b.c
index abc9892..bd2e220 100644 (file)
--- a/06b.c
+++ b/06b.c
@@ -2,33 +2,32 @@
 #include <stdlib.h>
 #include <string.h>
 
+#include <gmp.h>
+
 int main()
 {
-       char buf[1000];
-       if (fgets(buf, 1000, stdin) == NULL)
-               return 1;
-       long fish0[9] = {0};
-       long fish1[9] = {0};
-       long *this = &fish0[0];
-       long *that = &fish1[0];
+       char *buf = NULL;
+       size_t len = 0;
+       mpz_t fish[9];
+       for (int i = 0; i<9; i++)
+               mpz_init_set_ui(fish[i], 0);
 
+       getline(&buf, &len, stdin);
        char *p = strtok(buf, ",");
-       this[atoi(p)]++;
-       while ((p = strtok(NULL, ",")) != NULL)
-               this[atoi(p)]++;
+       int n = atoi(p);
+       mpz_add_ui(fish[n], fish[n], 1);
+       while ((p = strtok(NULL, ",")) != NULL) {
+               n = atoi(p);
+               mpz_add_ui(fish[n], fish[n], 1);
+       }
 
        for (long day = 0; day<256; day++) {
-               that[8] = this[0];
-               for (long i = 0; i<8; i++)
-                       that[i] = this[i+1];
-               that[6] += this[0];
-               long *tmp = this;
-               this = that;
-               that = tmp;
+               n = (day+7) % 9;
+               mpz_add(fish[n], fish[n], fish[day%9]);
        }
 
-       long sum = 0;
-       for (long i = 0; i<=8; i++)
-               sum += this[i];
-       printf("%lu\n", sum);
+       for (long i = 1; i<=8; i++)
+               mpz_add(fish[0], fish[0], fish[i]);
+       mpz_out_str(stdout, 10, fish[0]);
+       putchar('\n');
 }