From e57f82e16ce6fb903c6568dbc67a78937c0c8fa4 Mon Sep 17 00:00:00 2001 From: Ian C Date: Thu, 9 Dec 2021 20:31:05 +0000 Subject: Changed day 6 to a method hinted at on-line. --- 6.c | 39 ++++++++++++++++----------------------- 6a.c | 40 ++++++++++++++-------------------------- 2 files changed, 30 insertions(+), 49 deletions(-) diff --git a/6.c b/6.c index 8476b74..b0c1048 100644 --- a/6.c +++ b/6.c @@ -2,8 +2,6 @@ #include #include -#define MAX_BOARDS 100 - static char *ReadLine(char *p, size_t size, FILE *fp) { if ((p=fgets(p, size, fp))) @@ -22,8 +20,8 @@ static char *ReadLine(char *p, size_t size, FILE *fp) int main(void) { char buff[1024]; - int *num = NULL; - int num_count = 0; + unsigned long long num[9] = {0}; + unsigned long long num_count = 0; char *p = NULL; int f = 0; int cycle = 0; @@ -34,36 +32,31 @@ int main(void) while(p) { - num = realloc(num, (num_count + 1) * sizeof *num); - num[num_count++] = atoi(p); + num[atoi(p)]++; p = strtok(NULL, ","); } for(cycle = 0; cycle < 80; cycle++) { - int to_add = 0; + unsigned long long zero = 0; - for(f = 0; f < num_count; f++) - { - if (num[f] == 0) - { - to_add++; - num[f] = 6; - } - else - { - num[f]--; - } - } + zero = num[0]; - for(f = 0; f < to_add; f++) + for(f=0; f < 8; f++) { - num = realloc(num, (num_count + 1) * sizeof *num); - num[num_count++] = 8; + num[f] = num[f+1]; } + + num[6] += zero; + num[8] = zero; + } + + for(f = 0; f < 9; f++) + { + num_count += num[f]; } - printf("num_count=%d\n", num_count); + printf("num_count=%llu\n", num_count); return 0; } diff --git a/6a.c b/6a.c index da667f2..8949db5 100644 --- a/6a.c +++ b/6a.c @@ -2,8 +2,6 @@ #include #include -#define MAX_BOARDS 100 - static char *ReadLine(char *p, size_t size, FILE *fp) { if ((p=fgets(p, size, fp))) @@ -22,10 +20,10 @@ static char *ReadLine(char *p, size_t size, FILE *fp) int main(void) { char buff[1024]; - char *num = NULL; + unsigned long long num[9] = {0}; unsigned long long num_count = 0; char *p = NULL; - unsigned long long f = 0; + int f = 0; int cycle = 0; ReadLine(buff, sizeof buff, stdin); @@ -34,38 +32,28 @@ int main(void) while(p) { - num = realloc(num, (num_count + 1) * sizeof *num); - num[num_count++] = atoi(p); + num[atoi(p)]++; p = strtok(NULL, ","); } for(cycle = 0; cycle < 256; cycle++) { - int to_add = 0; + unsigned long long zero = 0; - for(f = 0; f < num_count; f++) - { - if (num[f] == 0) - { - to_add++; - num[f] = 6; - } - else - { - num[f]--; - } - } + zero = num[0]; - if (to_add) + for(f=0; f < 8; f++) { - num = realloc(num, (num_count + to_add) * sizeof *num); - for(f = 0; f < to_add; f++) - { - num[num_count++] = 8; - } + num[f] = num[f+1]; } - printf("cycle/num_count = %d/%llu\n", cycle, num_count); + num[6] += zero; + num[8] = zero; + } + + for(f = 0; f < 9; f++) + { + num_count += num[f]; } printf("num_count=%llu\n", num_count); -- cgit v1.2.3