Day 18 - Advent of Code 2024
18 December 2024
Working solutions for the day 18 puzzles.
Part One
""" day_18_01.py """
# usage: python3 day_18_01.py 70 1024 < input
import sys
def options(loc, space, track, obstacles):
""" options from loc within space avoiding obstacles but off track """
output = []
deltas = [(0, -1), (1, 0), (0, 1), (-1, 0)]
x0, y0 = loc
for dx, dy in deltas:
xd, yd = x0 + dx, y0 + dy
if all([0 <= xd < space, 0 <= yd < space,
(xd, yd) not in track, (xd, yd) not in obstacles]):
output.append((xd, yd))
return output
size = int(sys.argv[1]) + 1
count = int(sys.argv[2])
with sys.stdin as infile:
corrupt = {tuple(map(int, row.split(',')))
for i, row in enumerate(infile) if i < count}
goal = (size - 1, size - 1)
pos = (0, 0)
steps = 0
checked = []
choices = []
while pos != goal:
ways = options(pos, size, [c for c, _ in choices] + checked, corrupt)
for w in ways:
choices.append((w, steps + 1))
checked.append(pos)
pos, steps = choices.pop(0)
print(steps)
Part Two
""" day_18_02.py """
# usage: python3 day_18_02.py 70 < input
import sys
def options(loc, space, track, obstacles):
""" options from loc within space avoiding obstacles but off track """
output = []
deltas = [(0, -1), (1, 0), (0, 1), (-1, 0)]
x0, y0 = loc
for dx, dy in deltas:
xd, yd = x0 + dx, y0 + dy
if all([0 <= xd < space, 0 <= yd < space,
(xd, yd) not in track, (xd, yd) not in obstacles]):
output.append((xd, yd))
return output
size = int(sys.argv[1]) + 1
with sys.stdin as infile:
corrupt = [tuple(map(int, row.split(','))) for row in infile]
goal = (size - 1, size - 1)
for i in range(len(corrupt) + 1):
corrupted = set(corrupt[:i])
checked = []
pos = (0, 0)
choices = [pos]
while choices:
pos = choices.pop(0)
if pos == goal:
break
if ways := options(pos, size, choices + checked, corrupted):
choices.extend(ways)
checked.append(pos)
if pos != goal:
break
print(corrupt[i - 1])