1
0
Fork 0

update 2024/day6

better variable names
This commit is contained in:
Sebastian Mark 2024-12-06 15:43:33 +01:00
parent a16162adfd
commit 7803e54583

View file

@ -28,7 +28,7 @@ def find_guard(maze: list) -> tuple:
return tuple(-1, -1)
def move_guard(maze: list, guard: tuple) -> tuple[int, bool, dict]:
def move_guard(maze: list, guard_pos: tuple) -> tuple[int, bool, dict]:
width = len(maze[0])
height = len(maze)
@ -36,7 +36,7 @@ def move_guard(maze: list, guard: tuple) -> tuple[int, bool, dict]:
# remember the start position as visited
visited = set()
visited.add(guard)
visited.add(guard_pos)
# start upwards
direction = (0, -1)
@ -44,13 +44,13 @@ def move_guard(maze: list, guard: tuple) -> tuple[int, bool, dict]:
while True:
# get next position
nxt = (
guard[0] + direction[0],
guard[1] + direction[1],
guard_pos[0] + direction[0],
guard_pos[1] + direction[1],
)
# check borders
if not (0 <= nxt[0] < width and 0 <= nxt[1] < height):
visited.add(guard)
visited.add(guard_pos)
break
# check for obstacle and rotate clockwise
@ -61,13 +61,13 @@ def move_guard(maze: list, guard: tuple) -> tuple[int, bool, dict]:
# loop detection
# (has the guard been here and walking in the same direction?)
if nxt not in path_history:
path_history[nxt] = (guard, direction)
elif path_history[nxt] == (guard, direction):
path_history[nxt] = (guard_pos, direction)
elif path_history[nxt] == (guard_pos, direction):
return 0, True, {}
# mark spot as visited and move guard
visited.add(guard)
guard = nxt
visited.add(guard_pos)
guard_pos = nxt
return len(visited), False, path_history
@ -81,23 +81,23 @@ def print_maze(maze: list):
def main():
# part 1
maze = readinput()
guard = find_guard(maze)
count, _, guard_path = move_guard(maze, guard)
guard_pos = find_guard(maze)
count, _, guard_path = move_guard(maze, guard_pos)
print("Guard positions: %d" % count)
# part 2
count = 0
maze = readinput()
guard = find_guard(maze)
guard_pos = find_guard(maze)
# place an obstacle at every position in the guards path
# then check new maze for loop
for col, row in guard_path:
if (col, row) == guard:
if (col, row) == guard_pos:
continue
new_maze = deepcopy(maze)
new_maze[row][col] = "#"
_, loop, _ = move_guard(new_maze, guard)
_, loop, _ = move_guard(new_maze, guard_pos)
if loop:
count += 1