diff options
Diffstat (limited to '23.c')
-rw-r--r-- | 23.c | 62 |
1 files changed, 47 insertions, 15 deletions
@@ -3,6 +3,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <unistd.h> #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); |