/aoc-2024-day-15.js Secret
Last active
December 15, 2024 19:50
AoC 2024 Day 15
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { pipe } from "@/lib/utils.js"; | |
// prettier-ignore | |
const CMD = { "^": [-1, 0], ">": [0, 1], "v": [1, 0], "<": [0, -1], }; | |
const parse = (input, [g, cmds] = input.split("\n\n")) => [ | |
g.split("\n").map(row => [...row]), | |
[...cmds.split("\n").join("")].map(c => CMD[c]), | |
]; | |
const run = ([grid, commands]) => { | |
let py = grid.findIndex(row => row.includes("@")); | |
let px = grid[py].indexOf("@"); | |
commands.forEach(([dy, dx]) => { | |
const move = (y, x) => { | |
const c = grid[y][x]; | |
if (".#".includes(c)) { | |
return c === "."; | |
} | |
if (move(y + dy, x + dx)) { | |
grid[y + dy][x + dx] = c; | |
return true; | |
} | |
return false; | |
}; | |
if (move(py, px)) { | |
grid[py][px] = "."; | |
py = py + dy; | |
px = px + dx; | |
} | |
}); | |
return grid; | |
}; | |
const score = grid => | |
grid | |
.flatMap((row, y) => | |
row.map((c, x) => | |
"[O".includes(c) ? 100 * y + x : 0 | |
) | |
) | |
.reduce((sum, v) => sum + v); | |
export const part1 = pipe(parse, run, score); | |
const scaleX = ([grid, commands]) => [ | |
grid.map(row => | |
row.flatMap( | |
c => ({ O: ["[", "]"], "@": ["@", "."] }[c] ?? [c, c]) | |
) | |
), | |
commands, | |
]; | |
const run2 = ([grid, commands]) => { | |
let py = grid.findIndex(row => row.includes("@")); | |
let px = grid[py].indexOf("@"); | |
commands.forEach(([dy, dx]) => { | |
const testMove = (y, x) => { | |
const c = grid[y][x]; | |
if (".#".includes(c)) return c === "."; | |
if (dx || c === "@") return testMove(y + dy, x + dx); | |
return ( | |
testMove(y + dy, x + (c === "[" ? 1 : -1)) && | |
testMove(y + dy, x) | |
); | |
}; | |
const move = (y, x) => { | |
const c = grid[y][x]; | |
if ("." === c) return; | |
if (dx || c === "@") { | |
move(y + dy, x + dx); | |
grid[y + dy][x + dx] = c; | |
} else { | |
const x2 = x + (c === "[" ? 1 : -1); | |
move(y + dy, x2); | |
move(y + dy, x); | |
grid[y + dy][x] = c; | |
grid[y + dy][x2] = c === "[" ? "]" : "["; | |
grid[y][x2] = "."; | |
} | |
}; | |
if (testMove(py, px)) { | |
move(py, px); | |
grid[py][px] = "."; | |
py = py + dy; | |
px = px + dx; | |
} | |
}); | |
return grid; | |
}; | |
export const part2 = pipe(parse, scaleX, run2, score); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment