2017 day 18
This commit is contained in:
parent
b8ffad6c79
commit
96178dfda0
52
2017/18/duet.py
Executable file
52
2017/18/duet.py
Executable file
|
@ -0,0 +1,52 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
import sys
|
||||||
|
from multiprocessing import Queue
|
||||||
|
from multiprocessing.pool import ThreadPool
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
data = [l.strip().split(" ") for l in sys.stdin.readlines()]
|
||||||
|
|
||||||
|
def run(ident, rcvqueue, sndqueue):
|
||||||
|
reg = defaultdict(int)
|
||||||
|
reg['p'] = ident
|
||||||
|
pos, times_sent, played = 0, 0, None
|
||||||
|
|
||||||
|
def parse(word):
|
||||||
|
try:
|
||||||
|
return int(word)
|
||||||
|
except ValueError:
|
||||||
|
return reg[word]
|
||||||
|
|
||||||
|
while 0 <= pos < len(data) - 1:
|
||||||
|
ins = data[pos]
|
||||||
|
if ins[0] == 'snd':
|
||||||
|
played = parse(ins[1])
|
||||||
|
if sndqueue:
|
||||||
|
sndqueue.put(parse(ins[1]))
|
||||||
|
times_sent += 1
|
||||||
|
print(times_sent)
|
||||||
|
elif ins[0] == 'set':
|
||||||
|
reg[ins[1]] = parse(ins[2])
|
||||||
|
elif ins[0] == 'add':
|
||||||
|
reg[ins[1]] += parse(ins[2])
|
||||||
|
elif ins[0] == 'mul':
|
||||||
|
reg[ins[1]] *= parse(ins[2])
|
||||||
|
elif ins[0] == 'mod':
|
||||||
|
reg[ins[1]] %= parse(ins[2])
|
||||||
|
elif ins[0] == 'rcv':
|
||||||
|
if rcvqueue:
|
||||||
|
reg[ins[1]] = rcvqueue.get()
|
||||||
|
elif parse(ins[1]) > 0:
|
||||||
|
return played
|
||||||
|
elif ins[0] == 'jgz':
|
||||||
|
pos += parse(ins[2])
|
||||||
|
continue
|
||||||
|
pos += 1
|
||||||
|
return times_sent
|
||||||
|
|
||||||
|
print('Part 1:', run(0, None, None))
|
||||||
|
pool = ThreadPool(processes=2)
|
||||||
|
q1, q2 = Queue(), Queue()
|
||||||
|
p1, p2 = pool.apply_async(run, (0, q1, q2)), pool.apply_async(run, (0, q2, q1))
|
||||||
|
p1.get()
|
||||||
|
print('Part 2:', p2.get())
|
Loading…
Reference in New Issue
Block a user