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 2019/24

+97
+97
2019/day24.py
··· 1 + import fileinput 2 + from utils import Point 3 + 4 + 5 + def solve_part_1(board): 6 + def serialize(board): 7 + res = '' 8 + for y in range(5): 9 + res += ''.join(board[Point(x, y)] for x in range(5)) 10 + return res 11 + 12 + def diversity_score(board): 13 + return sum(2 ** i if c == '#' else 0 for i, c in enumerate(serialize(board))) 14 + 15 + seen = set() 16 + 17 + while True: 18 + new_board = {} 19 + for p in board: 20 + count = 0 21 + for np in p.neighbours_4(): 22 + if board.get(np, '.') == '#': 23 + count += 1 24 + 25 + if board.get(p, '.') == '#': 26 + new_board[p] = '#' if count == 1 else '.' 27 + else: 28 + new_board[p] = '#' if count == 1 or count == 2 else '.' 29 + 30 + if serialize(new_board) in seen: 31 + return diversity_score(new_board) 32 + 33 + seen.add(serialize(new_board)) 34 + board = new_board 35 + 36 + 37 + def solve_part_2(board): 38 + def recursive_neighbours(x, y, z): 39 + for np in Point(x, y).neighbours_4(): 40 + if np.x == 2 and np.y == 2: 41 + for i in range(5): 42 + if x == 1: 43 + yield (0, i, z + 1) 44 + elif x == 3: 45 + yield (4, i, z + 1) 46 + elif y == 1: 47 + yield (i, 0, z + 1) 48 + elif y == 3: 49 + yield (i, 4, z + 1) 50 + elif np.x == -1: 51 + yield (1, 2, z - 1) 52 + elif np.x == 5: 53 + yield (3, 2, z - 1) 54 + elif np.y == -1: 55 + yield (2, 1, z - 1) 56 + elif np.y == 5: 57 + yield (2, 3, z - 1) 58 + else: 59 + yield (np.x, np.y, z) 60 + 61 + 62 + for minutes in range(200): 63 + new_board = {} 64 + 65 + for z in range(-201, 201): 66 + for y in range(5): 67 + for x in range(5): 68 + if x == 2 and y == 2: 69 + continue 70 + 71 + count = 0 72 + for nx, ny, nz in recursive_neighbours(x, y, z): 73 + if board.get((nx, ny, nz), '.') == '#': 74 + count += 1 75 + 76 + if board.get((x, y, z), '.') == '#': 77 + new_board[(x, y, z)] = '#' if count == 1 else '.' 78 + else: 79 + new_board[(x, y, z)] = '#' if count == 1 or count == 2 else '.' 80 + 81 + board = new_board 82 + 83 + return board.values().count('#') 84 + 85 + 86 + # Read problem input 87 + PART_1 = {} 88 + PART_2 = {} 89 + 90 + for y, line in enumerate(fileinput.input()): 91 + for x, c in enumerate(line.strip()): 92 + PART_1[Point(x, y)] = c 93 + if not (x == 2 and y == 2): 94 + PART_2[(x, y, 0)] = c 95 + 96 + print "Biodiversity rating for first repeated layout:", solve_part_1(PART_1) 97 + print "Bugs in recursive space after 200 minutes:", solve_part_2(PART_2)