Skip to content

Commit dedf17f

Browse files
committed
Add solution to 2024-12-15
1 parent 7ab4578 commit dedf17f

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

2024/day15/solutions.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
with open("input") as f:
2+
ls, moves = f.read().strip().split("\n\n")
3+
4+
dirs = {"^": -1, "v": 1, "<": -1j, ">": 1j}
5+
moves = list(map(dirs.__getitem__, moves.replace("\n", "")))
6+
board = {i + 1j * j: x for i, l in enumerate(ls.split("\n")) for j, x in enumerate(l)}
7+
8+
9+
def solve(part2):
10+
walls = {z for z, x in board.items() if x == "#"}
11+
boxes = {z for z, x in board.items() if x == "O"}
12+
robot = next(z for z, x in board.items() if x == "@")
13+
if part2:
14+
walls = {w.real + 2 * w.imag * 1j for w in walls}
15+
walls |= {z + 1j for z in walls}
16+
# For part 2, only track the left side of the boxes
17+
boxes = {b.real + 2 * b.imag * 1j for b in boxes}
18+
robot = robot.real + 2 * robot.imag * 1j
19+
for dz in moves:
20+
to_move = set()
21+
to_check = [robot + dz]
22+
while to_check:
23+
z = to_check.pop()
24+
is_right_side = part2 and z - 1j in boxes
25+
if z in boxes or is_right_side:
26+
to_move.add(z)
27+
to_check.append(z + dz)
28+
if part2 and dz.real:
29+
other = z - 1j if is_right_side else z + 1j
30+
to_move.add(other)
31+
to_check.append(other + dz)
32+
elif z in walls:
33+
break
34+
else:
35+
to_move = to_move & boxes
36+
boxes -= to_move
37+
boxes |= {w + dz for w in to_move}
38+
robot += dz
39+
return sum(z.real * 100 + z.imag for z in boxes)
40+
41+
42+
# Part 1
43+
print(solve(False))
44+
45+
# Part 2
46+
print(solve(True))

0 commit comments

Comments
 (0)