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

+130
+130
2023/day14.py
··· 1 + import copy 2 + import fileinput 3 + 4 + from utils import Point, N, S, E, W 5 + 6 + 7 + # Parse problem input. 8 + BOARD = {} 9 + for y, line in enumerate(fileinput.input()): 10 + for x, c in enumerate(line.strip()): 11 + BOARD[Point(x, y)] = c 12 + 13 + WIDTH = x + 1 14 + HEIGHT = y + 1 15 + 16 + 17 + def tilt(board, direction): 18 + if direction == N: 19 + for y in range(1, HEIGHT): 20 + for x in range(WIDTH): 21 + p = Point(x, y) 22 + if board[p] != 'O': 23 + continue 24 + 25 + while p.y > 0: 26 + np = p + S 27 + if board[np] == '.': 28 + board[p] = '.' 29 + board[np] = 'O' 30 + else: 31 + break 32 + p = np 33 + 34 + elif direction == S: 35 + for y in reversed(range(HEIGHT - 1)): 36 + for x in range(WIDTH): 37 + p = Point(x, y) 38 + if board[p] != 'O': 39 + continue 40 + 41 + while p.y < HEIGHT - 1: 42 + np = p + N 43 + if board[np] == '.': 44 + board[p] = '.' 45 + board[np] = 'O' 46 + else: 47 + break 48 + p = np 49 + 50 + elif direction == E: 51 + for x in reversed(range(WIDTH)): 52 + for y in range(HEIGHT): 53 + p = Point(x, y) 54 + if board[p] != 'O': 55 + continue 56 + 57 + while p.x < WIDTH - 1: 58 + np = p + E 59 + if board[np] == '.': 60 + board[p] = '.' 61 + board[np] = 'O' 62 + else: 63 + break 64 + p = np 65 + 66 + elif direction == W: 67 + for x in range(1, WIDTH): 68 + for y in range(HEIGHT): 69 + p = Point(x, y) 70 + if board[p] != 'O': 71 + continue 72 + 73 + while p.x > 0: 74 + np = p + W 75 + if board[np] == '.': 76 + board[p] = '.' 77 + board[np] = 'O' 78 + else: 79 + break 80 + p = np 81 + 82 + 83 + def spin_cycle(board): 84 + for x in [N, W, S, E]: 85 + tilt(board, x) 86 + 87 + 88 + def total_load(board): 89 + return sum(HEIGHT - p.y for p, c in board.items() if c == 'O') 90 + 91 + 92 + def serialize(board): 93 + s = '' 94 + for y in range(HEIGHT): 95 + for x in range(WIDTH): 96 + s += board[Point(x, y)] 97 + 98 + return s 99 + 100 + 101 + # Solve part 1. 102 + part_1_board = copy.deepcopy(BOARD) 103 + tilt(part_1_board, N) 104 + print("Part 1:", total_load(part_1_board)) 105 + 106 + 107 + # Detect cycle length. 108 + board_states = {} 109 + 110 + c = 1 111 + while True: 112 + spin_cycle(BOARD) 113 + 114 + s = serialize(BOARD) 115 + if s in board_states: 116 + cycle_len = c - board_states[s] 117 + print(f"Determined period = {cycle_len} on iteration {c}.") 118 + break 119 + else: 120 + board_states[s] = c 121 + 122 + c += 1 123 + 124 + # Simulate further ahead to work out part 2 answer. 125 + while c % cycle_len != 1000000000 % cycle_len: 126 + spin_cycle(BOARD) 127 + c += 1 128 + 129 + print("Part 2:", total_load(BOARD)) 130 +