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 2017/18

+127
+84
2017/day18.py
··· 1 + import fileinput 2 + from collections import deque, defaultdict 3 + 4 + 5 + def duet_program(ops, regs, snd_q, rcv_q, part_1=False): 6 + pc = 0 7 + sends = 0 8 + 9 + while 0 <= pc < len(ops): 10 + op, x, y = ops[pc] 11 + y = regs[y] if y.isalpha() else int(y) 12 + 13 + if op == 'snd': 14 + snd_q.appendleft(regs[x] if x.isalpha() else int(x)) 15 + sends += 1 16 + elif op == 'set': 17 + regs[x] = y 18 + elif op == 'add': 19 + regs[x] += y 20 + elif op == 'mul': 21 + regs[x] *= y 22 + elif op == 'mod': 23 + regs[x] %= y 24 + elif op == 'rcv': 25 + if part_1: 26 + raise StopIteration 27 + else: 28 + if len(rcv_q) > 0: 29 + regs[x] = rcv_q.pop() 30 + else: 31 + yield op, sends 32 + continue 33 + elif op == 'jgz': 34 + if (regs[x] if x.isalpha() else int(x)) > 0: 35 + pc += y 36 + yield op, sends 37 + continue 38 + 39 + pc += 1 40 + yield op, sends 41 + 42 + raise StopIteration 43 + 44 + 45 + # Read puzzle input 46 + OPS = [] 47 + 48 + for line in fileinput.input(): 49 + parts = line.strip().split() 50 + op, x = parts[:2] 51 + y = 'foo' if len(parts) == 2 else parts[2] 52 + OPS.append((op, x, y)) 53 + 54 + 55 + # Part 1 56 + regs = defaultdict(int) 57 + snd_queue = deque() 58 + 59 + for _ in duet_program(OPS, regs, snd_queue, deque(), part_1=True): 60 + pass 61 + 62 + print "Value of recovered frequency:", snd_queue[0] 63 + 64 + 65 + # Part 2 66 + regs_0 = defaultdict(int) 67 + regs_1 = defaultdict(int) 68 + regs_0['p'] = 0 69 + regs_1['p'] = 1 70 + 71 + queue_0 = deque() 72 + queue_1 = deque() 73 + 74 + last_op_0 = None 75 + last_op_1 = None 76 + 77 + program_0 = duet_program(OPS, regs_0, queue_1, queue_0) 78 + program_1 = duet_program(OPS, regs_1, queue_0, queue_1) 79 + 80 + while not (last_op_0 == last_op_1 == 'rcv' and len(queue_0) == len(queue_1) == 0): 81 + last_op_0, _ = next(program_0) 82 + last_op_1, sends = next(program_1) 83 + 84 + print "Number of times program 1 sent a value:", sends
+41
2017/inputs/18.txt
··· 1 + set i 31 2 + set a 1 3 + mul p 17 4 + jgz p p 5 + mul a 2 6 + add i -1 7 + jgz i -2 8 + add a -1 9 + set i 127 10 + set p 952 11 + mul p 8505 12 + mod p a 13 + mul p 129749 14 + add p 12345 15 + mod p a 16 + set b p 17 + mod b 10000 18 + snd b 19 + add i -1 20 + jgz i -9 21 + jgz a 3 22 + rcv b 23 + jgz b -1 24 + set f 0 25 + set i 126 26 + rcv a 27 + rcv b 28 + set p a 29 + mul p -1 30 + add p b 31 + jgz p 4 32 + snd a 33 + set a b 34 + jgz 1 3 35 + snd b 36 + set f 1 37 + add i -1 38 + jgz i -11 39 + snd a 40 + jgz f -16 41 + jgz a -19
+2
2017/outputs/18.txt
··· 1 + 4601 2 + 6858