-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.py
146 lines (117 loc) · 3 KB
/
solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
input = [x for x in open("data.txt","r").read().split("\n")]
def isInt(s):
try:
int(s)
return True
except ValueError:
return False
def Value(s):
global reg
if isInt(s):
return int(s)
else:
if s not in reg: reg[s] = 0
return reg[s]
# First part
reg = {}
LastSound = 0
i = 0
while i < input.__len__():
ins = input[i].split(" ")
if ins[0] == "snd":
LastSound = Value(ins[1])
i += 1
continue
if ins[0] == "set":
reg[ins[1]] = Value(ins[2])
i += 1
continue
if ins[0] == "add":
reg[ins[1]] = Value(ins[1]) + Value(ins[2])
i += 1
continue
if ins[0] == "mul":
reg[ins[1]] = Value(ins[1]) * Value(ins[2])
i += 1
continue
if ins[0] == "mod":
reg[ins[1]] = Value(ins[1]) % Value(ins[2])
i += 1
continue
if ins[0] == "rcv":
if Value(ins[1]) != 0:
reg[ins[1]] = LastSound
break
if ins[0] == "jgz":
if Value(ins[1]) != 0:
i += Value(ins[2])
else:
i += 1
print("First part: " + str(LastSound))
# Second part
reg = [{"p": 0}, {"p": 1}]
queue = [[], []]
pointer = [0, 0]
counter = [0, 0]
def Value2(s, id):
global reg
if isInt(s):
return int(s)
else:
if s not in reg[id]: reg[id][s] = 0
return reg[id][s]
def ProgramStep(id):
global reg
global pointer
global input
global queue
global counter
if pointer[id] >= input.__len__():
return False
if pointer[id] < 0:
pointer[id] = input.__len__()
return False
ins = input[pointer[id]].split(" ")
if ins[0] == "snd":
queue[id-1].append(Value2(ins[1], id))
pointer[id] += 1
counter[id] += 1
return True
if ins[0] == "set":
reg[id][ins[1]] = Value2(ins[2], id)
pointer[id] += 1
return True
if ins[0] == "add":
reg[id][ins[1]] = Value2(ins[1], id) + Value2(ins[2], id)
pointer[id] += 1
return True
if ins[0] == "mul":
reg[id][ins[1]] = Value2(ins[1], id) * Value2(ins[2], id)
pointer[id] += 1
return True
if ins[0] == "mod":
reg[id][ins[1]] = Value2(ins[1], id) % Value2(ins[2], id)
pointer[id] += 1
return True
if ins[0] == "rcv":
if queue[id].__len__()>0:
reg[id][ins[1]] = queue[id][0]
queue[id].pop(0)
pointer[id] += 1
return True
else:
return False
if ins[0] == "jgz":
if Value2(ins[1], id) > 0:
pointer[id] += Value2(ins[2], id)
else:
pointer[id] += 1
return True
while True:
while ProgramStep(0):
pass
while ProgramStep(1):
pass
if queue[0].__len__() == 0 and queue[1].__len__() == 0: break
if pointer[0] >= input.__len__() and pointer[1] >= input.__len__(): break
print("Second part: " + str(counter[1]))