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 day11.py

+13 -14
+13 -14
2016/day11.py
··· 3 3 from itertools import combinations 4 4 5 5 6 - def complete(state): 7 - return all(f == 3 for f in state) 8 - 9 - 10 6 def valid(state): 7 + """Returns whether the current state is valid or not.""" 11 8 gens = set(state[::2]) 12 9 for i, floor in enumerate(state): 13 10 # Element is a chip if it has an odd index 14 11 if i % 2 == 1: 15 - # Its matching generator is on the same floor, so it's fine 16 - if state[i-1] == floor: 12 + # Chip's matching generator is on the same floor 13 + if state[i - 1] == floor: 17 14 continue 18 15 19 16 # There is another generator on the floor ··· 24 21 25 22 26 23 def ordered(state): 27 - substate = sorted(zip(state[::2], state[1::2])) 28 - return tuple(item for subl in substate for item in subl) 24 + """Returns an ordered version of the state (to improve node pruning).""" 25 + sorted_state = sorted(zip(state[::2], state[1::2])) 26 + return tuple(item for subl in sorted_state for item in subl) 29 27 30 28 31 29 def solve(state, start_floor=0): 32 - if start_floor == 3 and complete(state): 33 - return 0 34 - 35 30 horizon = [(start_floor, state)] 36 31 steps = 0 37 32 seen = set() ··· 43 38 can_move = [i for i, f in enumerate(state) if f == floor] 44 39 moves = [] 45 40 46 - if floor < 3: 41 + if floor < TOP_FLOOR: 47 42 moves.extend([(2, floor + 1), (1, floor + 1)]) 48 43 49 44 if floor > 0: ··· 65 60 for move in combinations(can_move, n): 66 61 next_state = tuple(new_floor if i in move else f for i, f in enumerate(state)) 67 62 68 - if complete(next_state): 63 + # All items are on the top floor, so we're done 64 + if all(f == TOP_FLOOR for f in next_state): 69 65 return steps + 1 70 66 71 67 if valid(next_state) and (new_floor, ordered(next_state)) not in seen: ··· 81 77 steps += 1 82 78 83 79 80 + TOP_FLOOR = None 84 81 generators = {} 85 82 microchips = {} 86 83 ··· 90 87 for chip in re.findall(r'(\w+)-compatible microchip', line): 91 88 microchips[chip] = i 92 89 90 + TOP_FLOOR = i 91 + 93 92 94 93 STATE = [] 95 94 ··· 102 101 print "Minimum number of steps:", solve(STATE) 103 102 104 103 STATE = tuple(list(STATE) + [0, 0, 0, 0]) 105 - print "With four new objects:", solve(STATE) 104 + print "Including 4 new objects:", solve(STATE)