Index: aoc2015.c ================================================================== --- aoc2015.c +++ aoc2015.c @@ -1,26 +1,21 @@ #include #include #include -#include #include "aocdailies.h" #include "aocutils.h" struct House { int row, col; }; -#ifndef MAX_HOUSES -# define MAX_HOUSES 2400 -#else -# error MAX_HOUSES already defined -#endif void aoc201503(char *data, size_t len) { (void)len; // unused argument char *data2 = data; // save it - struct House house[MAX_HOUSES] = {0}; - unsigned nhouse = 1; // house at [0, 0] visited + struct House *house = malloc(512 * sizeof *house); // assume it worked + unsigned mhouse = 512, nhouse = 1; + house[0].row = house[0].col = 0; // house at [0, 0] visited int x = 0, y = 0; while (*data) { switch (*data) { default: break; case '^': y++; break; @@ -35,28 +30,33 @@ visited = true; break; } } if (!visited) { - if (nhouse == MAX_HOUSES) { - fprintf(stderr, "Need more houses in aoc201503()\n"); - exit(EXIT_FAILURE); + if (nhouse == mhouse) { + // grow the array (by golden ratio) + struct House *tmp = realloc(house, (13*mhouse) / 8 * sizeof *house); + if (!tmp) { + fprintf(stderr, "no memory. program aborted\n"); + exit(EXIT_FAILURE); + } + house = tmp; + mhouse = (13*mhouse) / 8; } house[nhouse].row = x; house[nhouse].col = y; nhouse += 1; } } printf("Santa delivered at least 1 present to %u houses.\n", nhouse); - memset(house, 0, sizeof house); - nhouse = 1; - struct House p[2] = {0}; - int who = 1; // 0: santa; 1: santa bot + // reuse house array for part 2; don't worry about its contents + nhouse = 1; // house at [0, 0] still visited :) + struct House p[2] = {0}; // coordinates of santa and bot + int who = 0; // 0: santa; 1: santa bot // go around from the beginning while (*data2) { - who = 1 - who; // santa; bot; santa; bot; ..., ..., ... switch (*data2) { default: break; case '^': p[who].row++; break; case 'v': p[who].row--; break; case '>': p[who].col++; break; @@ -69,22 +69,28 @@ visited = true; break; } } if (!visited) { - if (nhouse == MAX_HOUSES) { - fprintf(stderr, "Need more houses in aoc201503()\n"); - exit(EXIT_FAILURE); + if (nhouse == mhouse) { + // grow the array (by golden ratio) + struct House *tmp = realloc(house, (13*mhouse) / 8 * sizeof *house); + if (!tmp) { + fprintf(stderr, "no memory. program aborted\n"); + exit(EXIT_FAILURE); + } + house = tmp; + mhouse = (13*mhouse) / 8; } house[nhouse].row = p[who].row; house[nhouse].col = p[who].col; nhouse += 1; } + who = 1 - who; // santa; bot; santa; bot; ..., ..., ... } printf("Santa and santa bot delivered at least 1 present to %u houses.\n", nhouse); } -#undef MAX_HOUSES void aoc201502(char *data, size_t len) { (void)len; // unused argument unsigned sqf = 0, f = 0; for (;;) {