Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Solution to Day 18: Duet - Part 2
#!/bin/python
#aoc_d18.py
inp = open('input_d18.txt','r').readlines()
regs = {0:{'p':0},1:{'p':1}}
pc = {0:0,1:0}
queues = {0: [], 1:[]}
sends = {0:0,1:0}
prg_run = 0
import re
while True:
i = inp[pc[prg_run]]
print "Program: ",prg_run,", Ins: ",i
if i.startswith("set"):
m = re.match("set\s([a-z])\s(-?\d+)",i)
if m:
regs[prg_run][m.group(1)] = int(m.group(2))
else:
m = re.match("set\s([a-z])\s([a-z])",i)
regs[prg_run][m.group(1)] = regs[prg_run][m.group(2)]
if i.startswith("add"):
m = re.match("add\s([a-z])\s(-?\d+)",i)
if m:
regs[prg_run][m.group(1)] += int(m.group(2))
else:
m = re.match("add\s([a-z])\s([a-z])",i)
regs[prg_run][m.group(1)] += regs[prg_run][m.group(2)]
if i.startswith("mul"):
m = re.match("mul\s([a-z])\s([a-z])",i)
if m:
regs[prg_run][m.group(1)] *= regs[prg_run][m.group(2)]
else:
m = re.match("mul\s([a-z])\s(-?\d+)",i)
regs[prg_run][m.group(1)] *= int(m.group(2))
if i.startswith("snd"):
m = re.match("snd\s([a-z])",i)
queues[(prg_run+1)%2].append(regs[prg_run][m.group(1)])
sends[prg_run] += 1
print 'Snd:',prg_run," -> ",len(queues[prg_run]),(prg_run+1)%2," -> ",len(queues[(prg_run+1)%2])
if i.startswith("mod"):
m = re.match("mod\s([a-z])\s(-?\d+)",i)
if m:
regs[prg_run][m.group(1)] %= int(m.group(2))
else:
m = re.match("mod\s([a-z])\s([a-z])",i)
regs[prg_run][m.group(1)] %= regs[prg_run][m.group(2)]
if i.startswith("rcv"):
print prg_run," -> ",len(queues[prg_run]),(prg_run+1)%2," -> ",len(queues[(prg_run+1)%2])
m = re.match("rcv\s([a-z])",i)
if len(queues[prg_run]) == 0:
prg_run = (prg_run + 1)%2
print "break?"
if inp[pc[prg_run]].startswith("rcv") and len(queues[prg_run]) == 0:
break
continue
v = queues[prg_run][0]
regs[prg_run][m.group(1)] = v
queues[prg_run] = queues[prg_run][1:]
if i.startswith("jgz"):
m = re.match("jgz\s([a-z])\s(-?\d+)",i)
if m:
if regs[prg_run][m.group(1)] > 0:
pc[prg_run] += int(m.group(2))
continue
m = re.match("jgz\s([a-z])\s([a-z])",i)
if m:
if regs[prg_run][m.group(1)] > 0:
pc[prg_run] += regs[prg_run][m.group(2)]
continue
m = re.match("jgz\s(\d+)\s(\d+)",i)
if m:
if int(m.group(1)) > 0:
pc[prg_run] += int(m.group(2))
continue
pc[prg_run] += 1
prg_run = (prg_run + 1)%2
if pc[prg_run] >= len(inp):
break
print sends
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment