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 naive BFS solution for 2016/11

+100
+100
2016/day11.py
··· 1 + import re 2 + import fileinput 3 + from itertools import combinations 4 + 5 + 6 + def complete(state): 7 + return all(f == 3 for f in state) 8 + 9 + 10 + def valid(state): 11 + gens = set(state[::2]) 12 + for i, floor in enumerate(state): 13 + # Element is a chip if it has an odd index 14 + if i % 2 == 1: 15 + # Its matching generator is on the same floor, so it's fine 16 + if state[i-1] == floor: 17 + continue 18 + 19 + # There is another generator on the floor 20 + if floor in gens: 21 + return False 22 + 23 + return True 24 + 25 + 26 + 27 + def solve(state, start_floor=0): 28 + if start_floor == 3 and complete(state): 29 + return 0 30 + 31 + horizon = [(start_floor, state)] 32 + steps = 0 33 + seen = set() 34 + 35 + while horizon: 36 + new_horizon = [] 37 + 38 + for floor, state in horizon: 39 + can_move = [i for i, f in enumerate(state) if f == floor] 40 + moves = [] 41 + 42 + if floor < 3: 43 + moves.extend([(2, floor + 1), (1, floor + 1)]) 44 + 45 + if floor > 0: 46 + moves.extend([(1, floor - 1), (2, floor - 1)]) 47 + 48 + moved_two_up = False 49 + moved_one_down = False 50 + 51 + for n, new_floor in moves: 52 + # Don't move one item up if you can move two, 53 + # and don't move two items down if can move one 54 + if n == 1 and new_floor > floor and moved_two_up: 55 + continue 56 + elif n == 2 and new_floor < floor and moved_one_down: 57 + continue 58 + 59 + for move in combinations(can_move, n): 60 + next_state = tuple(new_floor if i in move else f for i, f in enumerate(state)) 61 + 62 + if complete(next_state): 63 + return steps + 1 64 + 65 + if valid(next_state) and (new_floor, next_state) not in seen: 66 + pair = (new_floor, next_state) 67 + new_horizon.append(pair) 68 + seen.add(pair) 69 + 70 + if n == 2 and new_floor > floor: 71 + moved_two_up = True 72 + if n == 1 and new_floor < floor: 73 + moved_one_down = True 74 + 75 + horizon = new_horizon 76 + steps += 1 77 + 78 + 79 + generators = {} 80 + microchips = {} 81 + 82 + for i, line in enumerate(fileinput.input()): 83 + for gen in re.findall(r'(\w+) generator', line): 84 + generators[gen] = i 85 + for chip in re.findall(r'(\w+)-compatible microchip', line): 86 + microchips[chip] = i 87 + 88 + 89 + STATE = [] 90 + 91 + for key in generators: 92 + STATE.append(generators[key]) 93 + STATE.append(microchips[key]) 94 + 95 + STATE = tuple(STATE) 96 + 97 + print "Minimum number of steps:", solve(STATE) 98 + 99 + STATE = tuple(list(STATE) + [0, 0, 0, 0]) 100 + print "With four new objects:", solve(STATE)