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 solution for 2019/23

+83 -3
+74
2019/day23.py
··· 1 + import os 2 + import sys 3 + import time 4 + import fileinput 5 + import threading 6 + from collections import deque 7 + 8 + from intcode import emulate 9 + 10 + 11 + TAPE = [int(x) for x in fileinput.input()[0].split(',')] 12 + TAPE += [0] * 1000 13 + 14 + VMS = 50 15 + PACKET_QUEUES = [deque([i]) for i in range(VMS)] 16 + NAT = [None, None] 17 + 18 + 19 + def start_nic(pid): 20 + vm = emulate(TAPE, PACKET_QUEUES[pid], consume_input=True) 21 + 22 + while True: 23 + addr = next(vm) 24 + x = next(vm) 25 + y = next(vm) 26 + 27 + if addr == 255: 28 + NAT[0] = x 29 + NAT[1] = y 30 + else: 31 + PACKET_QUEUES[addr].extend([x, y]) 32 + 33 + 34 + def start_nat(): 35 + first_nat = False 36 + seen = set() 37 + 38 + while True: 39 + if NAT[1] is not None: 40 + if not first_nat: 41 + print "First Y value sent to NAT:", NAT[1] 42 + first_nat = True 43 + 44 + if not any(PACKET_QUEUES): 45 + x, y = NAT 46 + if y in seen: 47 + print "Value delivered by NAT twice in a row:", y 48 + os._exit(1) 49 + seen.add(y) 50 + 51 + PACKET_QUEUES[0].extend(NAT) 52 + NAT[0] = None 53 + NAT[1] = None 54 + 55 + time.sleep(1) 56 + 57 + 58 + threads = [] 59 + 60 + sys.stdout.write("Starting NICs and NAT") 61 + for pid in range(VMS): 62 + t = threading.Thread(target=start_nic, args=(pid,)) 63 + threads.append(t) 64 + t.start() 65 + sys.stdout.write(".") 66 + sys.stdout.flush() 67 + 68 + t = threading.Thread(target=start_nat) 69 + threads.append(t) 70 + t.start() 71 + sys.stdout.write("!\n") 72 + 73 + for t in threads: 74 + t.join()
+9 -3
2019/intcode.py
··· 37 37 return op, mode_a, mode_b, mode_c 38 38 39 39 40 - def emulate(tape, inputs, pc=0, relative_base=0, debug=False): 40 + def emulate(tape, inputs, pc=0, relative_base=0, debug=False, consume_input=False): 41 41 tape = tape[:] 42 42 ipc = 0 43 43 ··· 99 99 100 100 # INP a 101 101 elif op == 3: 102 - tape[a] = inputs[ipc % len(inputs)] 103 - ipc += 1 102 + if consume_input: 103 + if len(inputs) == 0: 104 + tape[a] = -1 105 + else: 106 + tape[a] = inputs.popleft() 107 + else: 108 + tape[a] = inputs[ipc % len(inputs)] 109 + ipc += 1 104 110 pc += 2 105 111 106 112 # OUT b