Skip to content

Commit

Permalink
feat: 2024 Day 15 Part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
mfulton26 committed Dec 17, 2024
1 parent 23e33db commit 26d5edc
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
46 changes: 46 additions & 0 deletions 2024/day/15/part/1/solve.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import solve from "./solve.ts";

import { assertEquals } from "@std/assert";

Deno.test("smaller example", () => {
const input = `\
########
#..O.O.#
##@.O..#
#...O..#
#.#.O..#
#...O..#
#......#
########
<^^>>>vv<v>>v<<`;

assertEquals(solve(input), 2028);
});

Deno.test("large example", () => {
const input = `\
##########
#..O..O.O#
#......O.#
#.OO..O.O#
#..O@..O.#
#O#..O...#
#O..O..O.#
#.OO.O.OO#
#....O...#
##########
<vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^
vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v
><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv<
<<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^
^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^><
^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^
>^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^
<><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<>
^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v>
v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^`;

assertEquals(solve(input), 10092);
});
34 changes: 34 additions & 0 deletions 2024/day/15/part/1/solve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const moveToDir = { "^": [0, -1], "v": [0, 1], "<": [-1, 0], ">": [1, 0] };

export default function solve(input: string) {
const [top, bottom] = input.split("\n\n");
const grid = top.split("\n").map((line) => [...line]);
const moves = bottom.replaceAll("\n", "");
let py = grid.findIndex((row) => row.includes("@")),
px = grid[py].indexOf("@");
function swap(x1: number, y1: number, x2: number, y2: number) {
[grid[y1][x1], grid[y2][x2]] = [grid[y2][x2], grid[y1][x1]];
}
for (const move of moves) {
const [dx, dy] = moveToDir[move as keyof typeof moveToDir];
let canMove = false, [wx, wy] = [px + dx, py + dy];
while (grid[wy][wx] !== "#") {
canMove ||= grid[wy][wx] === ".", wx += dx, wy += dy;
}
if (!canMove) continue;
let d = 0;
while (grid[py + (d + 1) * dy][px + (d + 1) * dx] !== ".") d++;
for (; d; d--) {
swap(px + d * dx, py + d * dy, px + (d + 1) * dx, py + (d + 1) * dy);
}
swap(px, py, px + dx, py + dy);
px += dx, py += dy;
}
let sum = 0;
for (let y = 0; y < grid.length; y++) {
for (let x = 0; x < grid[y].length; x++) {
if (grid[y][x] === "O") sum += 100 * y + x;
}
}
return sum;
}

0 comments on commit 26d5edc

Please sign in to comment.