+/AoC

advent of code

git clone https://git.julia.blue/+/AoC

Joseph RyanStart 2018!38c0746

master
2.4 KiB125 linesraw
1import os
2
3instructions = map(str.split, open("input.txt").readlines())
4
5reg = {chr(i): 0 for i in range(ord('a'), ord('z') + 1)}
6
7freq = 0
8line = 0
9firstTime = True
10soundEnabled = True
11
12
13def fset(x, y):
14    reg[x] = int(y)
15
16
17def fadd(x, y):
18    reg[x] += int(y)
19
20
21def fmul(x, y):
22    reg[x] *= int(y)
23
24
25def fmod(x, y):
26    reg[x] %= int(y)
27
28
29def fjgz(x, y):
30    global line
31    if int(x) > 0:
32        line += int(y) - 1
33
34
35def frcv(x, y):
36    global firstTime
37    if reg[x] != 0 and firstTime:
38        firstTime = False
39        return True
40
41
42def fsnd(x, y):
43    global freq, soundEnabled
44    freq = int(x)
45    if soundEnabled:
46        os.system("beep -f" + str(x))
47
48
49functions = {
50    "set": fset,
51    "add": fadd,
52    "mul": fmul,
53    "mod": fmod,
54    "jgz": fjgz,
55    "rcv": frcv,
56    "snd": fsnd
57}
58
59while line < len(instructions):
60    current = instructions[line]
61    arg1 = current[1]
62    if 'a' <= arg1 <= 'z' and current[0] in ("snd", "jgz"):
63        arg1 = reg[arg1]
64    arg2 = None
65    if len(current) > 2:
66        arg2 = current[2]
67        if 'a' <= arg2 <= 'z':
68            arg2 = reg[arg2]
69    if functions[current[0]](arg1, arg2):
70        break
71    line += 1
72
73print "Part 1:", freq
74
75waiting = [False, False]
76reg = {i: 0 for i in reg}
77altreg = dict(reg)
78altreg['p'] = 1
79line = 0
80altline = 0
81from collections import deque
82queue = [deque(), deque()]
83prog1sent = 0
84
85
86def fsend(x, y):
87    global prog, prog1sent
88    queue[not prog].append(int(x))
89    prog1sent += (prog == 1)
90
91
92def freceive(x, y):
93    global prog
94    waiting[prog] = x
95
96
97functions["snd"] = fsend
98functions["rcv"] = freceive
99
100while False in waiting or any(len(i) > 0 for i in queue):
101    for prog in range(2):
102        if waiting[prog]:
103            if len(queue[prog]):
104                reg[waiting[prog]] = queue[prog].popleft()
105                waiting[prog] = False
106            else:
107                reg, altreg = altreg, reg
108                line, altline = altline, line
109                continue
110
111        current = instructions[line]
112        arg1 = current[1]
113        if 'a' <= arg1 <= 'z' and current[0] in ("snd", "jgz"):
114            arg1 = reg[arg1]
115        arg2 = None
116        if len(current) > 2:
117            arg2 = current[2]
118            if 'a' <= arg2 <= 'z':
119                arg2 = reg[arg2]
120        functions[current[0]](arg1, arg2)
121        line += 1
122        line, altline = altline, line
123        reg, altreg = altreg, reg
124
125print "Part 2:", prog1sent