diff --git a/2023/day10/part2.ts b/2023/day10/part2.ts index 3692f70..c239f62 100644 --- a/2023/day10/part2.ts +++ b/2023/day10/part2.ts @@ -1,6 +1,200 @@ export function answer(input: string): number { - console.log(input); - return 42; + const m = input.split("\n").map((l) => l.split("")); + const loop = findMainLoop(m); + + // Update the S tile to what it should actually be + m[loop[0].y][loop[0].x] = tileFromDirs([ + dirFromCoord(loop[0], loop[loop.length - 1])!, + dirFromCoord(loop[0], loop[1])!, + ]); + + const isInPath = ({ x, y }: Coord, p: Path): boolean => + p.some((s) => s.x === x && s.y === y); + + const inCache = new Array(m.length) + .fill(null) + .map(() => new Array(m[0].length).fill(null)); + + for (const [y, row] of m.entries()) { + let inBounds = false; + let state: "out" | "in" | "on" = "out"; + let lastFlip; + for (const [x, curr] of row.entries()) { + if (isInPath({ x, y }, loop)) { + state = "on"; + if ("|J7LF".includes(curr)) { + if ( + !lastFlip || + curr === "|" || + ("|L".includes(lastFlip) && curr === "J") || + ("|F".includes(lastFlip) && curr === "7") + ) { + inBounds = !inBounds; + lastFlip = curr; + } + } + } else { + state = inBounds ? "in" : "out"; + } + inCache[y][x] = state; + } + } + console.log( + inCache + .map((row, y) => + row + .map((c, x) => { + if (c === "on") return newChar(m[y][x]); + if (c === "in") return "x"; + return "."; + }) + .join(""), + ) + .join("\n"), + ); + return inCache + .map((row) => row.map((c) => (c === "in" ? 1 : 0))) + .flat() + .reduce((sum, x) => sum + x, 0); +} + +const newChar = (c: string): string => { + switch (c) { + case "F": + return "┌"; + case "7": + return "┐"; + case "L": + return "└"; + case "J": + return "┘"; + case "-": + return "─"; + case "|": + return "│"; + } + return c; +}; + +const tileFromDirs = (dirs: [Dir, Dir]): string => { + switch (dirs.sort().join("")) { + case "EN": + return "L"; + case "ES": + return "F"; + case "EW": + return "-"; + case "NS": + return "|"; + case "NW": + return "J"; + case "SW": + return "7"; + } + throw "invalid dirs"; +}; + +type Dir = "N" | "S" | "E" | "W"; +const dirs: Dir[] = ["N", "S", "E", "W"]; + +type Map = string[][]; +type Coord = { x: number; y: number }; +type Path = [Coord, Coord, ...Coord[]]; + +const findStart = (m: Map): Coord => { + for (const [y, row] of m.entries()) { + for (const [x, c] of row.entries()) { + if (c === "S") return { x, y }; + } + } + throw "no start?!"; +}; + +const findMainLoop = (m: Map): Path => { + const start = findStart(m); + + const paths: Path[] = new Array(4) + .fill(null) + .map((_, i) => [start, move(start, dirs[i])]); + + for (const pathStart of paths) { + const path = followPath(m, pathStart); + if (isLoop(m, path)) return path; + } + throw "did not find main loop"; +}; + +const possibleDirs = (m: Map, c: Coord): Dir[] => { + switch (m[c.y][c.x]) { + case "|": + return ["N", "S"]; + case "-": + return ["W", "E"]; + case "L": + return ["N", "E"]; + case "J": + return ["N", "W"]; + case "7": + return ["S", "W"]; + case "F": + return ["S", "E"]; + case ".": + case "S": + default: + return []; + } +}; + +const dirFromCoord = (curr: Coord, target: Coord): Dir | null => { + if (sameCoords(move(curr, "N"), target)) return "N"; + if (sameCoords(move(curr, "S"), target)) return "S"; + if (sameCoords(move(curr, "E"), target)) return "E"; + if (sameCoords(move(curr, "W"), target)) return "W"; + return null; +}; + +const isInBounds = (m: Map, c: Coord): boolean => + c.x < m[0].length && c.y < m.length; + +const sameCoords = (c1: Coord, c2: Coord) => c1.x === c2.x && c1.y === c2.y; +const isLoop = (m: Map, p: Path) => { + const next = nextStep(m, p); + if (next === "end") return false; + return sameCoords(next, p[0]); +}; + +const move = ({ x, y }: Coord, d: Dir): Coord => { + switch (d) { + case "N": + return { x, y: y - 1 }; + case "S": + return { x, y: y + 1 }; + case "E": + return { x: x + 1, y }; + case "W": + return { x: x - 1, y }; + } +}; + +const nextStep = (m: Map, p: Path): Coord | "end" => { + const last = p[p.length - 1]; + const secondToLast = p[p.length - 2]; + const dir = possibleDirs(m, last).filter( + (d) => d !== dirFromCoord(last, secondToLast), + ); + if (dir.length !== 1) return "end"; + return move(last, dir[0]); +}; + +function followPath(m: Map, path: Path): Path { + let curr: Coord | "end" = path[1]; + do { + curr = nextStep(m, path); + if (curr === "end" || !isInBounds(m, curr) || isLoop(m, path)) break; + path.push(curr); + } while (!isLoop(m, path) || !isInBounds(m, curr)); + + return path; } if (import.meta.main) { diff --git a/2023/day10/puzzle.md b/2023/day10/puzzle.md index 057d273..75c4360 100644 --- a/2023/day10/puzzle.md +++ b/2023/day10/puzzle.md @@ -131,8 +131,134 @@ Here are the distances for each tile on that loop: Find 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?* -To begin, [get your puzzle input](10/input). +Your puzzle answer was `7145`. + +The first half of this puzzle is complete! It provides one gold star: \* + +\--- Part Two --- +---------- + +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*? + +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: + +``` +........... +.S-------7. +.|F-----7|. +.||.....||. +.||.....||. +.|L-7.F-J|. +.|..|.|..|. +.L--J.L--J. +........... + +``` + +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: + +``` +........... +.S-------7. +.|F-----7|. +.||OOOOO||. +.||OOOOO||. +.|L-7OF-J|. +.|II|O|II|. +.L--JOL--J. +.....O..... + +``` + +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: + +``` +.......... +.S------7. +.|F----7|. +.||OOOO||. +.||OOOO||. +.|L-7F-J|. +.|II||II|. +.L--JL--J. +.......... + +``` + +In both of the above examples, `*4*` tiles are enclosed by the loop. + +Here's a larger example: + +``` +.F----7F7F7F7F-7.... +.|F--7||||||||FJ.... +.||.FJ||||||||L7.... +FJL7L7LJLJ||LJ.L-7.. +L--J.L7...LJS7F-7L7. +....F-J..F7FJ|L7L7L7 +....L7.F7||L7|.L7L7| +.....|FJLJ|FJ|F7|.LJ +....FJL-7.||.||||... +....L---J.LJ.LJLJ... + +``` + +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`): + +``` +OF----7F7F7F7F-7OOOO +O|F--7||||||||FJOOOO +O||OFJ||||||||L7OOOO +FJL7L7LJLJ||LJIL-7OO +L--JOL7IIILJS7F-7L7O +OOOOF-JIIF7FJ|L7L7L7 +OOOOL7IF7||L7|IL7L7| +OOOOO|FJLJ|FJ|F7|OLJ +OOOOFJL-7O||O||||OOO +OOOOL---JOLJOLJLJOOO + +``` + +In this larger example, `*8*` tiles are enclosed by the loop. + +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: + +``` +FF7FSF7F7F7F7F7F---7 +L|LJ||||||||||||F--J +FL-7LJLJ||||||LJL-77 +F--JF--7||LJLJ7F7FJ- +L---JF-JLJ.||-FJLJJ7 +|F|F-JF---7F7-L7L|7| +|FFJF7L7F-JF7|JL---7 +7-L-JL7||F7|L7F-7F7| +L.L7LFJ|||||FJL7||LJ +L7JLJL-JLJLJL--JLJ.L + +``` + +Here are just the tiles that are *enclosed by the loop* marked with `I`: + +``` +FF7FSF7F7F7F7F7F---7 +L|LJ||||||||||||F--J +FL-7LJLJ||||||LJL-77 +F--JF--7||LJLJIF7FJ- +L---JF-JLJIIIIFJLJJ7 +|F|F-JF---7IIIL7L|7| +|FFJF7L7F-JF7IIL---7 +7-L-JL7||F7|L7F-7F7| +L.L7LFJ|||||FJL7||LJ +L7JLJL-JLJLJL--JLJ.L + +``` + +In this last example, `*10*` tiles are enclosed by the loop. + +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?* Answer: -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. \ No newline at end of file +Although it hasn't changed, you can still [get your puzzle input](10/input). + +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. \ No newline at end of file diff --git a/2023/day10/test.ts b/2023/day10/test.ts index 2164737..0a41e6b 100644 --- a/2023/day10/test.ts +++ b/2023/day10/test.ts @@ -2,17 +2,30 @@ import { assertEquals } from "https://deno.land/std@0.208.0/assert/mod.ts"; import * as p1 from "./part1.ts"; import * as p2 from "./part2.ts"; +// ..F7. +// .FJ|. +// SJ.L7 +// |F--J +// LJ... +const examples = ["..F7.", ".FJ|.", "SJ.L7", "|F--J", "LJ..."].join("\n"); +const examples2 = [ + "FF7FSF7F7F7F7F7F---7", + "L|LJ||||||||||||F--J", + "FL-7LJLJ||||||LJL-77", + "F--JF--7||LJLJ7F7FJ-", + "L---JF-JLJ.||-FJLJJ7", + "|F|F-JF---7F7-L7L|7|", + "|FFJF7L7F-JF7|JL---7", + "7-L-JL7||F7|L7F-7F7|", + "L.L7LFJ|||||FJL7||LJ", + "L7JLJL-JLJLJL--JLJ.L", +].join("\n"); Deno.test("part1", () => { - // ..F7. - // .FJ|. - // SJ.L7 - // |F--J - // LJ... - const examples = ["..F7.", ".FJ|.", "SJ.L7", "|F--J", "LJ..."].join("\n"); assertEquals(p1.answer(examples), 8); + assertEquals(p2.answer(examples2), 10); }); -// Deno.test("part2", () => { -// const examples = ["abc", "def"].join("\n"); -// assertEquals(p2.answer(examples), 42); -// }); +Deno.test("part2", () => { + assertEquals(p2.answer(examples), 1); + assertEquals(p2.answer(examples2), 10); +});