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.

Update day15.py

+40 -35
+40 -35
2019/day15.py
··· 6 6 from intcode import emulate 7 7 8 8 9 + ROBOT_DIRS = [ 10 + Point(1, 0), # north 11 + Point(-1, 0), # south 12 + Point(0, -1), # west 13 + Point(0, 1), # east 14 + ] 15 + 16 + INVERSE_DIRS = { 17 + 0: 1, 18 + 1: 0, 19 + 2: 3, 20 + 3: 2, 21 + } 22 + 23 + 24 + def robot_dfs(vm, graph, curr, approach_d): 25 + for d in range(4): 26 + np = curr + ROBOT_DIRS[d] 27 + if np in graph: 28 + continue 29 + 30 + # Attempt to move to next tile 31 + GLOBAL_INPUTS[0] = d + 1 32 + resp = next(vm) 33 + 34 + if resp == 0: 35 + BOARD[np] = 0 36 + else: 37 + if resp == 2: 38 + global OXYGEN 39 + OXYGEN = np 40 + BOARD[np] = resp 41 + robot_dfs(vm, graph, np, d) 42 + 43 + # Can't rely on call stack alone to backtrack 44 + GLOBAL_INPUTS[0] = INVERSE_DIRS[approach_d] + 1 45 + next(vm) 46 + 47 + 9 48 def bfs(graph, start, end=None): 10 49 seen = set() 11 50 dist = 0 ··· 39 78 BOARD = {} 40 79 OXYGEN = None 41 80 42 - ROBOT_DIRS = [ 43 - Point(1, 0), # north 44 - Point(-1, 0), # south 45 - Point(0, -1), # west 46 - Point(0, 1), # east 47 - ] 48 - 49 - 50 - # Build up board state by exploration 51 81 vm = emulate(TAPE, 0, GLOBAL_INPUTS) 52 - 53 - try: 54 - curr = Point(0, 0) 55 - for _ in range(1000000): 56 - facing = random.choice(xrange(4)) 57 - while BOARD.get(curr + ROBOT_DIRS[facing], 1) == 0: 58 - facing = random.choice(xrange(4)) 59 - 60 - GLOBAL_INPUTS[0] = facing + 1 61 - resp = next(vm) 62 - 63 - if resp == 0: 64 - BOARD[curr + ROBOT_DIRS[facing]] = 0 65 - elif resp == 1: 66 - curr += ROBOT_DIRS[facing] 67 - BOARD[curr] = 1 68 - elif resp == 2: 69 - curr += ROBOT_DIRS[facing] 70 - OXYGEN = curr 71 - BOARD[curr] = 2 72 - 73 - except StopIteration: 74 - pass 75 - 76 - # We should have found the oxygen tank after this many ticks 77 - assert 2 in BOARD.values() 82 + robot_dfs(vm, BOARD, Point(0, 0), 0) 78 83 79 84 print "Optimal movement to oxygen:", bfs(BOARD, Point(0, 0), OXYGEN) 80 85 print "Minutes taken to fill up:", bfs(BOARD, OXYGEN) - 1