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 2022/21

+56
+56
2022/day21.py
··· 1 + import copy 2 + import fileinput 3 + from collections import defaultdict 4 + 5 + from utils import topsort 6 + 7 + 8 + GRAPH = defaultdict(set) 9 + YELLS = {} 10 + 11 + for line in fileinput.input(): 12 + monkey, rest = line.strip().split(': ') 13 + if rest.isnumeric(): 14 + YELLS[monkey] = int(rest) 15 + else: 16 + d1, op, d2 = rest.split(' ') 17 + YELLS[monkey] = (d1, op, d2) 18 + GRAPH[monkey].add(d1) 19 + GRAPH[monkey].add(d2) 20 + 21 + ORDERING = list(reversed(topsort(GRAPH))) 22 + 23 + 24 + def simulate(yells, humn=None): 25 + if humn: 26 + yells['humn'] = humn 27 + d1, _, d2 = yells['root'] 28 + yells['root'] = (d1, "==", d2) 29 + 30 + for monkey in ORDERING: 31 + if type(yells[monkey]) != int: 32 + d1, op, d2 = yells[monkey] 33 + yells[monkey] = eval(f"{yells[d1]} {op} {yells[d2]}") 34 + 35 + return int(yells['root']) 36 + 37 + 38 + print("Part 1:", simulate(copy.deepcopy(YELLS))) 39 + 40 + # For my problem input, we analyze some values of the two monkeys that 41 + # the `root` monkey depends on, and how it changes depends on `humn`. 42 + # 43 + # humn=3 d1=72750855862944 d2=31522134274080 44 + # humn=8 d1=72750855862880 d2=31522134274080 45 + # 46 + # When `humn` increases by 5, `d1` decreases by 64, and `d2` is constant. 47 + # Therefore, we need to solve the following equation: 48 + # 49 + # humn = 3 + (72750855862944 - 31522134274080) * (5 / 64) 50 + # = 3220993874133 51 + 52 + HUMN = 3220993874133 53 + part_2 = simulate(copy.deepcopy(YELLS), humn=HUMN); assert part_2 == 1 54 + print("Part 2:", HUMN) 55 + 56 +