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.

Optimize 2017/22 solution

Use ints to store current position instead of Point objects. This speeds
up the grid lookups, reducing runtime from ~50s to ~10s.

+13 -10
+13 -10
2017/day22.py
··· 2 2 from utils import Point, DIRS 3 3 4 4 5 - def simulate_activity(pos, facing, grid, mapping): 6 - node = grid.get(pos, '.') 5 + def simulate_activity(x, y, facing, grid, mapping): 6 + node = grid.get((x, y), '.') 7 7 new_node, df = mapping[node] 8 8 9 9 # Update node 10 - grid[pos] = new_node 10 + grid[x, y] = new_node 11 11 12 12 # Update direction and position 13 13 nf = (facing + df) % 4 14 - pos += DIRS[nf] 14 + x += DIRS[nf].x 15 + y += DIRS[nf].y 15 16 16 - return pos, nf, new_node == '#' 17 + return x, y, nf, new_node == '#' 17 18 18 19 19 20 # Maps node transformations and turn-direction ··· 36 37 # Read puzzle input 37 38 for y, line in enumerate(fileinput.input()): 38 39 for x, c in enumerate(line.strip()): 39 - GRID[Point(x, y)] = c 40 + GRID[x, y] = c 40 41 41 42 WIDTH = x + 1 42 43 HEIGHT += 1 43 44 44 45 # Part 1 45 - pos = Point(WIDTH // 2, HEIGHT // 2) 46 + x = WIDTH // 2 47 + y = HEIGHT // 2 46 48 facing = 2 47 49 grid = GRID.copy() 48 50 infections_caused = 0 49 51 50 52 for _ in range(10000): 51 - pos, facing, caused = simulate_activity(pos, facing, grid, PART_1_MAP) 53 + x, y, facing, caused = simulate_activity(x, y, facing, grid, PART_1_MAP) 52 54 if caused: 53 55 infections_caused += 1 54 56 55 57 print "Infections caused in Part 1:", infections_caused 56 58 57 59 # Part 2 58 - pos = Point(WIDTH // 2, HEIGHT // 2) 60 + x = WIDTH // 2 61 + y = HEIGHT // 2 59 62 facing = 2 60 63 grid = GRID.copy() 61 64 infections_caused = 0 62 65 63 66 for _ in range(10000000): 64 - pos, facing, caused = simulate_activity(pos, facing, grid, PART_2_MAP) 67 + x, y, facing, caused = simulate_activity(x, y, facing, grid, PART_2_MAP) 65 68 if caused: 66 69 infections_caused += 1 67 70