From 985d8d2db0cb743f5fd1982b5c5af4615eb53931 Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Wed, 28 Dec 2022 14:58:43 +0000 Subject: Solve puzzle 23 part 2 --- 23.c | 62 +++++++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 15 deletions(-) (limited to '23.c') diff --git a/23.c b/23.c index 24d2c3d..99a3fb7 100644 --- a/23.c +++ b/23.c @@ -3,6 +3,7 @@ #include #include #include +#include #define arrlen(x) (sizeof(x)/sizeof((x)[0])) @@ -249,14 +250,36 @@ grid_dump(char * buf, int cols, int rows) int -main() +main(int argc, char ** argv) { + int rounds = 10; char * buf = NULL, * pch; int bufsiz = 0, buflen = 0; int cols, rows, round; int xmin, xmax, ymin, ymax, i, j; int empty; + while ((i = getopt(argc, argv, "p:r:")) != -1) { + switch (i) { + case 'p': + switch (atoi(optarg)) { + case 1: rounds = 10; break; + case 2: rounds = -1; break; + default: + fprintf(stderr, "Unexpected part %s\n", optarg); + return -1; + } + break; + + case 'r': + rounds = atoi(optarg); + break; + + default: + return -1; + } + } + // Read input while (1) { size_t n; @@ -294,9 +317,9 @@ main() } // Do rounds of movement simulation - for (round = 0; round < 10; ++round) { + for (round = 0; round < rounds || rounds < 0; ++round) { char * psrc, * pdest; - int dir; + int dir, moves = 0; // Get current bounding box. if (bounding(&xmin, &xmax, &ymin, &ymax, buf, cols, rows) != 0) { @@ -428,6 +451,7 @@ main() pdest = posd(buf, cols, rows, i, j, dir); *pdest = '#'; *psrc = '.'; + ++moves; } else if (loc_proposed(*psrc)) { // Clean up count of elves who wanted to move here. @@ -436,28 +460,36 @@ main() } } + if (!moves) + break; + #if 0 fprintf(stderr, "Round %d\n", round + 1); grid_dump(buf, cols, rows); #endif } - // Find the number of empty cells in the bounding box - empty = 0; - if (bounding(&xmin, &xmax, &ymin, &ymax, buf, cols, rows) != 0) { - fprintf(stderr, "Can't find bounding box!\n"); - free(buf); - return -1; + if (rounds < 0) { + printf("Number of rounds needed to stabilise: %d\n", round + 1); } - for (j = ymin; j < ymax; ++j) { - for (i = xmin; i < xmax; ++i) { - if (loc_clear(*pos(buf, cols, rows, i, j))) { - ++empty; + else { + // Find the number of empty cells in the bounding box + empty = 0; + if (bounding(&xmin, &xmax, &ymin, &ymax, buf, cols, rows) != 0) { + fprintf(stderr, "Can't find bounding box!\n"); + free(buf); + return -1; + } + for (j = ymin; j < ymax; ++j) { + for (i = xmin; i < xmax; ++i) { + if (loc_clear(*pos(buf, cols, rows, i, j))) { + ++empty; + } } } - } - printf("Number of empty spaces: %d\n", empty); + printf("Number of empty spaces after %d rounds: %d\n", rounds, empty); + } // Tidy and exit free(buf); -- cgit v1.2.1