Day 6 - Advent of Code 2024
6 December 2024
Working solutions for the day 6 puzzles.
Part One
""" day_06_01.py """
# usage: python3 day_06_01.py < input
import sys
def on_map(loc, across, down):
""" is loc within across by down """
if loc[0] in range(across) and loc[1] in range(down):
return True
return False
def step(loc, way, objects):
""" take a step or turn to avoid obstruction """
new = loc[0] + way[0], loc[1] + way[1]
if new in objects:
headings = [(0, -1), (1, 0), (0, 1), (-1, 0)]
return loc, headings[(headings.index(way) + 1) % 4]
return new, way
width, height = None, None
pos, bearing = None, None
obstructions = []
with sys.stdin as infile:
for j, line in enumerate(infile):
for i, x in enumerate(line.strip()):
if x == '#':
obstructions.append((i, j))
elif x == '^':
pos, bearing = (i, j), (0, -1)
width = i + 1
height = j + 1
visited = set()
while on_map(pos, width, height):
visited.add(pos)
pos, bearing = step(pos, bearing, obstructions)
print(len(visited))
Part Two
""" day_06_02.py """
# usage: python3 day_06_02.py < input
import sys
def on_map(loc, across, down):
""" is loc within across by down """
if loc[0] in range(across) and loc[1] in range(down):
return True
return False
def step(loc, way, objects):
""" take a step or turn to avoid obstruction """
new = loc[0] + way[0], loc[1] + way[1]
if new in objects:
headings = [(0, -1), (1, 0), (0, 1), (-1, 0)]
return loc, headings[(headings.index(way) + 1) % 4]
return new, way
width, height = None, None
start = None
obstructions = []
with sys.stdin as infile:
for j, line in enumerate(infile):
for i, x in enumerate(line.strip()):
if x == '#':
obstructions.append((i, j))
elif x == '^':
start = ((i, j), (0, -1))
width = i + 1
height = j + 1
loops = 0
for j in range(height):
for i in range(width):
if (i, j) in obstructions or (i, j) == start[0]:
continue
obstructions.append((i, j))
visited = set()
pos, bearing = start
while on_map(pos, width, height):
visited.add((pos, bearing))
pos, bearing = step(pos, bearing, obstructions)
if (pos, bearing) in visited:
loops += 1
break
obstructions.pop()
print(loops)