Compare commits

...

2 Commits

Author SHA1 Message Date
f1c5694d26 Day 6 part 2 solution. 2024-12-07 01:36:54 +10:00
baf45b78d1 Day 6 part 1 solution. 2024-12-07 00:43:14 +10:00
2 changed files with 307 additions and 0 deletions

272
day6/solver.py Normal file
View File

@@ -0,0 +1,272 @@
import sys
from copy import copy, deepcopy
import operator as op
from typing import Optional, Self, TypeAlias
import logging
logger = logging.getLogger()
class SimulationLooping(Exception):
...
class Direction:
steps = [(0, -1), (1, 0), (0, 1), (-1, 0)]
chars = ['^', '>', 'v', '<']
def __init__(self, angle: int):
self.angle = angle
@classmethod
def parse(cls, char: str):
angle = cls.chars.index(char)
return cls(angle)
@property
def step(self):
return self.steps[self.angle]
def __str__(self):
return self.chars[self.angle]
def __repr__(self):
return f"<Direction angle={self.angle} facing={str(self)}>"
def turn(self, amount=1):
return Direction((self.angle + amount) % 4)
def __hash__(self):
return hash(self.angle)
def __eq__(self, other):
return self.angle == other.angle
class Position:
__slots__ = ('x', 'y')
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __repr__(self):
return f"<Position x={self.x} y={self.y}>"
def move(self, direction: Direction):
xdiff, ydiff = direction.step
return Position(self.x + xdiff, self.y + ydiff)
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
return self.x == other.x and self.y == other.y
class LabMap:
def __init__(self, width: int, height: int, obstacles: set[Position]):
self.width = width
self.height = height
self.obstacles = obstacles
def in_map(self, pos: Position):
"""
Test whether a given position is in the map.
"""
return (0 <= pos.x < self.width) and (0 <= pos.y < self.height)
def is_obstacle(self, pos: Position):
"""
Test whether the position is an obstacle.
"""
return pos in self.obstacles
def __deepcopy__(self, memo):
return LabMap(self.width, self.height, copy(self.obstacles))
class Guard:
def __init__(self, pos: Optional[Position], direction: Direction):
self.pos = pos
self.direction = direction
self.visited: set[tuple[Position, Direction]] = set()
if pos is not None:
self.visited.add((pos, direction))
def visit(self, pos: Position):
self.pos = pos
key = (pos, self.direction)
seen_before = key in self.visited
self.visited.add(key)
return seen_before
def get_path(self):
return set(map(op.itemgetter(0), self.visited))
def leave(self):
self.pos = None
def total_visited(self):
return len(self.get_path())
def turn(self):
self.direction = self.direction.turn()
def __deepcopy__(self, memo):
guard = Guard(self.pos, self.direction)
guard.visited = copy(self.visited)
return guard
class Simulation:
def __init__(self, map: LabMap, guards: list[Guard]):
self.map = map
self.guards = guards
self.ticker = 0
def __deepcopy__(self, memo):
sim = Simulation(deepcopy(self.map, memo), deepcopy(self.guards, memo))
sim.ticker = self.ticker
return sim
@classmethod
def from_string(cls, simstring: str) -> Self:
"""
Create a Simulation from a starting string.
"""
if not simstring:
raise ValueError("Empty simulation string provided")
obstacles = []
guards = []
lines = simstring.splitlines()
width = len(lines[0])
height = len(lines)
for i, line in enumerate(simstring.splitlines()):
line = line.strip()
if not line:
continue
for j, char in enumerate(line):
match char:
case '#':
pos = Position(j, i)
obstacles.append(pos)
case '>' | 'v' | '<' | '^':
pos = Position(j, i)
direction = Direction.parse(char)
guard = Guard(pos, direction)
guards.append(guard)
case '.':
pass
case _:
logger.warning(f"Unknown map char: '{char}'")
map = LabMap(width, height, set(obstacles))
return cls(map, guards)
def to_string(self) -> str:
"""
Create a simulation map string.
Mainly for debugging.
"""
lines = []
# Initialise the list
for _ in range(self.map.height):
line = self.map.width * ['.']
lines.append(line)
for obstacle in self.map.obstacles:
lines[obstacle.y][obstacle.x] = '#'
for guard in self.guards:
pos = guard.pos
if pos is not None:
lines[pos.y][pos.x] = str(guard.direction)
return '\n'.join(''.join(line) for line in lines)
def total_visited(self) -> int:
return sum(guard.total_visited() for guard in self.guards)
def tick(self):
"""
Tick the simulation.
"""
looping = None
for guard in self.guards:
if (pos := guard.pos) is not None:
pos = pos.move(guard.direction)
if self.map.in_map(pos):
if self.map.is_obstacle(pos):
guard.turn()
else:
looper = guard.visit(pos)
looping = looper if looping is None else looping & looper
else:
guard.leave()
self.ticker += 1
if looping:
raise SimulationLooping("All guards are looping!")
# print(f"Tick {self.ticker}")
# print(self.to_string())
def run(self):
if not self.guards:
raise ValueError("Simulation has no guards to move!")
while any(guard.pos is not None for guard in self.guards):
self.tick()
def find_good_obstacles(sim: Simulation):
"""
Examine alternate universes to compute a list of good obstacle locations.
NOTE: This is far from the most efficient approach.
We could also memoise guard paths from each alt universe simulation
to 'fast-forward' time between changes.
"""
guard = sim.guards[0]
good_obstacles = []
tried_obstacles = set()
while any(guard.pos is not None for guard in sim.guards):
sim_alt = deepcopy(sim)
sim.tick()
pos = guard.pos
if pos is not None and pos not in tried_obstacles:
sim_alt.map.obstacles.add(pos)
try:
sim_alt.run()
except SimulationLooping:
good_obstacles.append(pos)
tried_obstacles.add(pos)
return good_obstacles
def main():
with open(sys.argv[1]) as file:
map = file.read().strip()
print("Loading Simulation")
simulation = Simulation.from_string(map)
print("Running Simulation")
simulation.run()
print(f"Simulation complete after {simulation.ticker} steps.")
print(f"Total nodes visited: {simulation.total_visited()}")
print("Loading Simulation again")
simulation = Simulation.from_string(map)
print("Searching alternate universes for good obtacle placement.")
result = find_good_obstacles(simulation)
print(f"Found {len(result)} good placements for obstacles!")
if __name__ == '__main__':
main()

35
day6/test.py Normal file
View File

@@ -0,0 +1,35 @@
from solver import Simulation, find_good_obstacles
test_data = r"""
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
""".strip()
def test_visited():
print("Beginning visited test")
sim = Simulation.from_string(test_data)
sim.run()
visited = sim.total_visited()
assert visited == 41
print("Visited test passed")
def test_loop_obstacles():
print("Beginning loop inducing obstacle placement test")
sim = Simulation.from_string(test_data)
places = find_good_obstacles(sim)
assert len(places) == 6
print(f"Loop inducing obstacle placement test complete")
if __name__ == '__main__':
test_visited()
test_loop_obstacles()