···11export function answer(input: string): number {
22- console.log(input);
33- return 42;
22+ const m = input.split("\n").map((l) => l.split(""));
33+ const loop = findMainLoop(m);
44+55+ // Update the S tile to what it should actually be
66+ m[loop[0].y][loop[0].x] = tileFromDirs([
77+ dirFromCoord(loop[0], loop[loop.length - 1])!,
88+ dirFromCoord(loop[0], loop[1])!,
99+ ]);
1010+1111+ const isInPath = ({ x, y }: Coord, p: Path): boolean =>
1212+ p.some((s) => s.x === x && s.y === y);
1313+1414+ const inCache = new Array(m.length)
1515+ .fill(null)
1616+ .map(() => new Array(m[0].length).fill(null));
1717+1818+ for (const [y, row] of m.entries()) {
1919+ let inBounds = false;
2020+ let state: "out" | "in" | "on" = "out";
2121+ let lastFlip;
2222+ for (const [x, curr] of row.entries()) {
2323+ if (isInPath({ x, y }, loop)) {
2424+ state = "on";
2525+ if ("|J7LF".includes(curr)) {
2626+ if (
2727+ !lastFlip ||
2828+ curr === "|" ||
2929+ ("|L".includes(lastFlip) && curr === "J") ||
3030+ ("|F".includes(lastFlip) && curr === "7")
3131+ ) {
3232+ inBounds = !inBounds;
3333+ lastFlip = curr;
3434+ }
3535+ }
3636+ } else {
3737+ state = inBounds ? "in" : "out";
3838+ }
3939+ inCache[y][x] = state;
4040+ }
4141+ }
4242+ console.log(
4343+ inCache
4444+ .map((row, y) =>
4545+ row
4646+ .map((c, x) => {
4747+ if (c === "on") return newChar(m[y][x]);
4848+ if (c === "in") return "x";
4949+ return ".";
5050+ })
5151+ .join(""),
5252+ )
5353+ .join("\n"),
5454+ );
5555+ return inCache
5656+ .map((row) => row.map((c) => (c === "in" ? 1 : 0)))
5757+ .flat()
5858+ .reduce<number>((sum, x) => sum + x, 0);
5959+}
6060+6161+const newChar = (c: string): string => {
6262+ switch (c) {
6363+ case "F":
6464+ return "┌";
6565+ case "7":
6666+ return "┐";
6767+ case "L":
6868+ return "└";
6969+ case "J":
7070+ return "┘";
7171+ case "-":
7272+ return "─";
7373+ case "|":
7474+ return "│";
7575+ }
7676+ return c;
7777+};
7878+7979+const tileFromDirs = (dirs: [Dir, Dir]): string => {
8080+ switch (dirs.sort().join("")) {
8181+ case "EN":
8282+ return "L";
8383+ case "ES":
8484+ return "F";
8585+ case "EW":
8686+ return "-";
8787+ case "NS":
8888+ return "|";
8989+ case "NW":
9090+ return "J";
9191+ case "SW":
9292+ return "7";
9393+ }
9494+ throw "invalid dirs";
9595+};
9696+9797+type Dir = "N" | "S" | "E" | "W";
9898+const dirs: Dir[] = ["N", "S", "E", "W"];
9999+100100+type Map = string[][];
101101+type Coord = { x: number; y: number };
102102+type Path = [Coord, Coord, ...Coord[]];
103103+104104+const findStart = (m: Map): Coord => {
105105+ for (const [y, row] of m.entries()) {
106106+ for (const [x, c] of row.entries()) {
107107+ if (c === "S") return { x, y };
108108+ }
109109+ }
110110+ throw "no start?!";
111111+};
112112+113113+const findMainLoop = (m: Map): Path => {
114114+ const start = findStart(m);
115115+116116+ const paths: Path[] = new Array(4)
117117+ .fill(null)
118118+ .map((_, i) => [start, move(start, dirs[i])]);
119119+120120+ for (const pathStart of paths) {
121121+ const path = followPath(m, pathStart);
122122+ if (isLoop(m, path)) return path;
123123+ }
124124+ throw "did not find main loop";
125125+};
126126+127127+const possibleDirs = (m: Map, c: Coord): Dir[] => {
128128+ switch (m[c.y][c.x]) {
129129+ case "|":
130130+ return ["N", "S"];
131131+ case "-":
132132+ return ["W", "E"];
133133+ case "L":
134134+ return ["N", "E"];
135135+ case "J":
136136+ return ["N", "W"];
137137+ case "7":
138138+ return ["S", "W"];
139139+ case "F":
140140+ return ["S", "E"];
141141+ case ".":
142142+ case "S":
143143+ default:
144144+ return [];
145145+ }
146146+};
147147+148148+const dirFromCoord = (curr: Coord, target: Coord): Dir | null => {
149149+ if (sameCoords(move(curr, "N"), target)) return "N";
150150+ if (sameCoords(move(curr, "S"), target)) return "S";
151151+ if (sameCoords(move(curr, "E"), target)) return "E";
152152+ if (sameCoords(move(curr, "W"), target)) return "W";
153153+ return null;
154154+};
155155+156156+const isInBounds = (m: Map, c: Coord): boolean =>
157157+ c.x < m[0].length && c.y < m.length;
158158+159159+const sameCoords = (c1: Coord, c2: Coord) => c1.x === c2.x && c1.y === c2.y;
160160+const isLoop = (m: Map, p: Path) => {
161161+ const next = nextStep(m, p);
162162+ if (next === "end") return false;
163163+ return sameCoords(next, p[0]);
164164+};
165165+166166+const move = ({ x, y }: Coord, d: Dir): Coord => {
167167+ switch (d) {
168168+ case "N":
169169+ return { x, y: y - 1 };
170170+ case "S":
171171+ return { x, y: y + 1 };
172172+ case "E":
173173+ return { x: x + 1, y };
174174+ case "W":
175175+ return { x: x - 1, y };
176176+ }
177177+};
178178+179179+const nextStep = (m: Map, p: Path): Coord | "end" => {
180180+ const last = p[p.length - 1];
181181+ const secondToLast = p[p.length - 2];
182182+ const dir = possibleDirs(m, last).filter(
183183+ (d) => d !== dirFromCoord(last, secondToLast),
184184+ );
185185+ if (dir.length !== 1) return "end";
186186+ return move(last, dir[0]);
187187+};
188188+189189+function followPath(m: Map, path: Path): Path {
190190+ let curr: Coord | "end" = path[1];
191191+ do {
192192+ curr = nextStep(m, path);
193193+ if (curr === "end" || !isInBounds(m, curr) || isLoop(m, path)) break;
194194+ path.push(curr);
195195+ } while (!isLoop(m, path) || !isInBounds(m, curr));
196196+197197+ return path;
4198}
51996200if (import.meta.main) {
+128-2
2023/day10/puzzle.md
···131131132132Find the single giant loop starting at `S`. *How many steps along the loop does it take to get from the starting position to the point farthest from the starting position?*
133133134134-To begin, [get your puzzle input](10/input).
134134+Your puzzle answer was `7145`.
135135+136136+The first half of this puzzle is complete! It provides one gold star: \*
137137+138138+\--- Part Two ---
139139+----------
140140+141141+You quickly reach the farthest point of the loop, but the animal never emerges. Maybe its nest is *within the area enclosed by the loop*?
142142+143143+To determine whether it's even worth taking the time to search for such a nest, you should calculate how many tiles are contained within the loop. For example:
144144+145145+```
146146+...........
147147+.S-------7.
148148+.|F-----7|.
149149+.||.....||.
150150+.||.....||.
151151+.|L-7.F-J|.
152152+.|..|.|..|.
153153+.L--J.L--J.
154154+...........
155155+156156+```
157157+158158+The above loop encloses merely *four tiles* - the two pairs of `.` in the southwest and southeast (marked `I` below). The middle `.` tiles (marked `O` below) are *not* in the loop. Here is the same loop again with those regions marked:
159159+160160+```
161161+...........
162162+.S-------7.
163163+.|F-----7|.
164164+.||OOOOO||.
165165+.||OOOOO||.
166166+.|L-7OF-J|.
167167+.|II|O|II|.
168168+.L--JOL--J.
169169+.....O.....
170170+171171+```
172172+173173+In fact, there doesn't even need to be a full tile path to the outside for tiles to count as outside the loop - squeezing between pipes is also allowed! Here, `I` is still within the loop and `O` is still outside the loop:
174174+175175+```
176176+..........
177177+.S------7.
178178+.|F----7|.
179179+.||OOOO||.
180180+.||OOOO||.
181181+.|L-7F-J|.
182182+.|II||II|.
183183+.L--JL--J.
184184+..........
185185+186186+```
187187+188188+In both of the above examples, `*4*` tiles are enclosed by the loop.
189189+190190+Here's a larger example:
191191+192192+```
193193+.F----7F7F7F7F-7....
194194+.|F--7||||||||FJ....
195195+.||.FJ||||||||L7....
196196+FJL7L7LJLJ||LJ.L-7..
197197+L--J.L7...LJS7F-7L7.
198198+....F-J..F7FJ|L7L7L7
199199+....L7.F7||L7|.L7L7|
200200+.....|FJLJ|FJ|F7|.LJ
201201+....FJL-7.||.||||...
202202+....L---J.LJ.LJLJ...
203203+204204+```
205205+206206+The above sketch has many random bits of ground, some of which are in the loop (`I`) and some of which are outside it (`O`):
207207+208208+```
209209+OF----7F7F7F7F-7OOOO
210210+O|F--7||||||||FJOOOO
211211+O||OFJ||||||||L7OOOO
212212+FJL7L7LJLJ||LJIL-7OO
213213+L--JOL7IIILJS7F-7L7O
214214+OOOOF-JIIF7FJ|L7L7L7
215215+OOOOL7IF7||L7|IL7L7|
216216+OOOOO|FJLJ|FJ|F7|OLJ
217217+OOOOFJL-7O||O||||OOO
218218+OOOOL---JOLJOLJLJOOO
219219+220220+```
221221+222222+In this larger example, `*8*` tiles are enclosed by the loop.
223223+224224+Any tile that isn't part of the main loop can count as being enclosed by the loop. Here's another example with many bits of junk pipe lying around that aren't connected to the main loop at all:
225225+226226+```
227227+FF7FSF7F7F7F7F7F---7
228228+L|LJ||||||||||||F--J
229229+FL-7LJLJ||||||LJL-77
230230+F--JF--7||LJLJ7F7FJ-
231231+L---JF-JLJ.||-FJLJJ7
232232+|F|F-JF---7F7-L7L|7|
233233+|FFJF7L7F-JF7|JL---7
234234+7-L-JL7||F7|L7F-7F7|
235235+L.L7LFJ|||||FJL7||LJ
236236+L7JLJL-JLJLJL--JLJ.L
237237+238238+```
239239+240240+Here are just the tiles that are *enclosed by the loop* marked with `I`:
241241+242242+```
243243+FF7FSF7F7F7F7F7F---7
244244+L|LJ||||||||||||F--J
245245+FL-7LJLJ||||||LJL-77
246246+F--JF--7||LJLJIF7FJ-
247247+L---JF-JLJIIIIFJLJJ7
248248+|F|F-JF---7IIIL7L|7|
249249+|FFJF7L7F-JF7IIL---7
250250+7-L-JL7||F7|L7F-7F7|
251251+L.L7LFJ|||||FJL7||LJ
252252+L7JLJL-JLJLJL--JLJ.L
253253+254254+```
255255+256256+In this last example, `*10*` tiles are enclosed by the loop.
257257+258258+Figure out whether you have time to search for the nest by calculating the area within the loop. *How many tiles are enclosed by the loop?*
135259136260Answer:
137261138138-You can also [Shareon [Twitter](https://twitter.com/intent/tweet?text=%22Pipe+Maze%22+%2D+Day+10+%2D+Advent+of+Code+2023&url=https%3A%2F%2Fadventofcode%2Ecom%2F2023%2Fday%2F10&related=ericwastl&hashtags=AdventOfCode) [Mastodon](javascript:void(0);)] this puzzle.262262+Although it hasn't changed, you can still [get your puzzle input](10/input).
263263+264264+You can also [Shareon [Twitter](https://twitter.com/intent/tweet?text=I%27ve+completed+Part+One+of+%22Pipe+Maze%22+%2D+Day+10+%2D+Advent+of+Code+2023&url=https%3A%2F%2Fadventofcode%2Ecom%2F2023%2Fday%2F10&related=ericwastl&hashtags=AdventOfCode) [Mastodon](javascript:void(0);)] this puzzle.