Index: aoc2024.c ================================================================== --- aoc2024.c +++ aoc2024.c @@ -9,14 +9,48 @@ /* === aoc202406 ======================================================= Hmmm, I've done something like this already this year... on day 4 I need rcmap() moved to aocutils ... done; now it's called `linearize2d` ===================================================================== */ + +static bool validpos(unsigned s, int r, int c) { + if (r < 0) return false; + if (c < 0) return false; + if ((unsigned)r >= s - 1) return false; + if ((unsigned)c >= s - 1) return false; + return true; +} + +static void rightturn(int *drow, int *dcol) { + if (*drow) { *dcol = -*drow; *drow = 0; } + else { *drow = *dcol; *dcol = 0; } +} void aoc202406(char *data, size_t len) { - (void)data; (void)len; + // assume data is well-formatted and has the same number of rows and columns + unsigned size = 1 + strchr(data, '\n') - data; + unsigned linear_pos = strchr(data, '^') - data; + int row_pos = (int)(linear_pos / size); + int col_pos = (int)(linear_pos % size); + int deltarow = -1, deltacol = 0; + //printf("character at [%u, %u] is '%c'\n", row_pos, col_pos, data[linearize2d(size, row_pos, col_pos)]); + unsigned visited = 1; + data[linearize2d(size, (unsigned)row_pos, (unsigned)col_pos)] = 'X'; // initial place visited + while (validpos(size, row_pos + deltarow, col_pos + deltacol)) { + switch (data[linearize2d(size, (unsigned)(row_pos+deltarow), (unsigned)(col_pos+deltacol))]) { + default: exit(EXIT_FAILURE); // does not happen + case '#': rightturn(&deltarow, &deltacol); break; + case '.': visited++; + data[linearize2d(size, (unsigned)(row_pos+deltarow), (unsigned)(col_pos+deltacol))] = 'X'; + /*fallthrough*/ + case 'X': row_pos += deltarow; + col_pos += deltacol; + break; + } + } + printf("The guard visits %u positions before leaving the area.\n", visited); } /* === aoc202405 ======================================================= ===================================================================== */