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 2022/14

+67
+67
2022/day14.py
··· 1 + import copy 2 + import fileinput 3 + 4 + from utils import parse_nums, chunks 5 + from utils import Point, N, NE, NW 6 + 7 + 8 + # Parse input. 9 + max_y = 0 10 + traces = [] 11 + for line in fileinput.input(): 12 + nums = parse_nums(line) 13 + trace = [] 14 + for x, y in chunks(nums, 2): 15 + trace.append(Point(x, y)) 16 + max_y = max(max_y, y) 17 + traces.append(trace) 18 + 19 + 20 + # Fill in the board with all the rock locations. 21 + board = {} 22 + for trace in traces: 23 + last = trace[0] 24 + for nxt in trace[1:]: 25 + if last.x == nxt.x: 26 + for y in range(min(last.y, nxt.y), max(last.y, nxt.y) + 1): 27 + board[Point(last.x, y)] = "#" 28 + else: 29 + for x in range(min(last.x, nxt.x), max(last.x, nxt.x) + 1): 30 + board[Point(x, last.y)] = "#" 31 + 32 + last = nxt 33 + 34 + 35 + def simulate(board, floor=100000000): 36 + board = copy.deepcopy(board) 37 + sand = source 38 + while True: 39 + if sand.y > 10000: 40 + return board 41 + 42 + # Inverted directions because this problem uses "+Y is down" convention. 43 + if board.get(sand + N, '.') not in ("#", "o") and sand.y + 1 < floor: 44 + sand += N 45 + continue 46 + elif board.get(sand + NW, '.') not in ("#", "o") and sand.y + 1 < floor: 47 + sand += NW 48 + continue 49 + elif board.get(sand + NE, '.') not in ("#", "o") and sand.y + 1 < floor: 50 + sand += NE 51 + continue 52 + elif sand == source: 53 + board[sand] = "o" 54 + return board 55 + else: 56 + board[sand] = "o" 57 + sand = source 58 + 59 + 60 + source = Point(500, 0) 61 + board[source] = "+" 62 + 63 + part_1_board = simulate(board) 64 + print("Part 1:", sum(1 for v in part_1_board.values() if v == "o")) 65 + 66 + part_2_board = simulate(board, floor=(max_y + 2)) 67 + print("Part 2:", sum(1 for v in part_2_board.values() if v == "o"))