Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Advent of Code 2024: Day 6
- from icecream import ic
- from collections import defaultdict
- from datetime import datetime
- time_start = datetime.now()
- def tuple_sum(a,b):
- return tuple([x + y for x, y in zip(a,b)])
- def create_grid(lines):
- grid = dict()
- guard = (0,0)
- for r, line in enumerate(lines):
- for c, char in enumerate(line):
- if char == "^":
- guard = (r,c)
- grid[(r,c)] = "."
- else:
- grid[(r,c)] = char
- return grid, guard
- def step_or_turn(guard, direction):
- dr, dc = directions[direction]
- r, c = guard
- new_position = ((r + dr, c + dc))
- if new_position in grid.keys():
- if grid[new_position] != "#":
- guard = new_position
- else:
- direction = (direction + 1) % 4
- else:
- guard = -1
- return guard, direction
- def loop_exists(start, in_directions):
- result = set()
- start = (8,2)
- in_directions = {3}
- for in_direction in in_directions:
- if start == (8,2) and in_direction == 3:
- print("got u")
- guard = start
- obsticle = tuple_sum(start, directions[in_direction])
- grid[obsticle] = "#"
- direction = (in_direction + 1) % 4
- visited = defaultdict(set)
- while guard in grid.keys():
- guard, direction = step_or_turn(guard, direction)
- if direction == in_direction and guard == start:
- ic(obsticle, direction, start)
- result.add(obsticle)
- break
- if guard != -1:
- visited[guard].add(direction)
- grid[obsticle] = "."
- return result
- #MAIN
- with open("test.txt") as file:
- lines = file.read().splitlines()
- grid, guard = create_grid(lines)
- directions = [(-1, 0), (0, 1), (1, 0), (0, -1)] # ULDR
- direction = 0
- path = defaultdict(set) # key = coord, value = set of visited directions
- path[guard].add(0) #first point is also visited
- while guard in grid.keys():
- guard, direction = step_or_turn(guard, direction)
- if guard != -1:
- path[guard].add(direction)
- print("Part 1:", len(path.keys()))
- loop_points = set()
- for start, in_dirs in path.items():
- loop_points |= loop_exists(start, in_dirs)
- print(loop_points)
- print(len(loop_points))
- print("Runtime:", datetime.now() - time_start)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement