My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add solution for 2023/16

+64
+64
2023/day16.py
··· 1 + import fileinput 2 + from utils import Point, DIRS, N, E, S, W 3 + 4 + 5 + # Parse problem input. 6 + GRID = {} 7 + for y, line in enumerate(fileinput.input()): 8 + for x, c in enumerate(line.strip()): 9 + GRID[Point(x, y)] = c 10 + 11 + MAX_X = x 12 + MAX_Y = y 13 + 14 + 15 + def simulate_light(grid, start, initial_d): 16 + photons = [(start, initial_d)] 17 + seen = set() 18 + while photons: 19 + photon, d = photons.pop() 20 + 21 + if photon not in grid: 22 + continue 23 + 24 + if (photon, d) in seen: 25 + continue 26 + 27 + seen.add((photon, d)) 28 + 29 + if grid[photon] == '.': 30 + photons.append((photon + d, d)) 31 + elif grid[photon] == '/': 32 + nd = [W, E, S, N][[N, S, E, W].index(d)] 33 + photons.append((photon + nd, nd)) 34 + elif grid[photon] == '\\': 35 + nd = [E, W, N, S][[N, S, E, W].index(d)] 36 + photons.append((photon + nd, nd)) 37 + elif grid[photon] == '|': 38 + if d in (N, S): 39 + photons.append((photon + d, d)) 40 + else: 41 + photons.append((photon + N, N)) 42 + photons.append((photon + S, S)) 43 + elif grid[photon] == '-': 44 + if d in (E, W): 45 + photons.append((photon + d, d)) 46 + else: 47 + photons.append((photon + E, E)) 48 + photons.append((photon + W, W)) 49 + 50 + return len(set(p for p, d in seen)) 51 + 52 + 53 + def part_2_starts(grid): 54 + for x in range(MAX_X): 55 + yield Point(x, 0), N 56 + yield Point(x, MAX_Y - 1), S 57 + 58 + for y in range(MAX_Y): 59 + yield Point(0, y), E 60 + yield Point(MAX_X - 1, y), W 61 + 62 + 63 + print("Part 1:", simulate_light(GRID, Point(0, 0), E)) 64 + print("Part 2:", max(simulate_light(GRID, p, d) for p, d in part_2_starts(GRID)))