From: Mart Lubbers Date: Mon, 6 Dec 2021 09:22:05 +0000 (+0100) Subject: use getline, experiment with gmp X-Git-Url: https://git.martlubbers.net/?a=commitdiff_plain;h=7ba426df9118b57ac5cc95085f89c91477a9a59f;p=advent21.git use getline, experiment with gmp --- diff --git a/06a.c b/06a.c index c9152c6..e2634d2 100644 --- a/06a.c +++ b/06a.c @@ -4,10 +4,11 @@ int main() { - char buf[1000]; - if (fgets(buf, 1000, stdin) == NULL) - return 1; + char *buf = NULL; + size_t len = 0; long fish[9] = {0}; + + getline(&buf, &len, stdin); char *p = strtok(buf, ","); fish[atoi(p)]++; while ((p = strtok(NULL, ",")) != NULL) @@ -16,8 +17,7 @@ int main() for (long day = 0; day<80; day++) fish[(day+7) % 9] += fish[day%9]; - long sum = 0; - for (long i = 0; i<=8; i++) - sum += fish[i]; - printf("%lu\n", sum); + for (long i = 1; i<=8; i++) + fish[0] += fish[i]; + printf("%ld\n", fish[0]); } diff --git a/06b.c b/06b.c index 0b2f076..bd2e220 100644 --- a/06b.c +++ b/06b.c @@ -2,22 +2,32 @@ #include #include +#include + int main() { - char buf[1000]; - if (fgets(buf, 1000, stdin) == NULL) - return 1; - long fish[9] = {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, ","); - fish[atoi(p)]++; - while ((p = strtok(NULL, ",")) != NULL) - fish[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++) - fish[(day+7) % 9] += fish[day%9]; + for (long day = 0; day<256; day++) { + n = (day+7) % 9; + mpz_add(fish[n], fish[n], fish[day%9]); + } - long sum = 0; - for (long i = 0; i<=8; i++) - sum += fish[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'); }