-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
intcode_assembler.py
56 lines (53 loc) · 1.57 KB
/
intcode_assembler.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
from typing import List
MNEMONICS = {
"NOP": [0, 0],
"ADD": [1, 3],
"MUL": [2, 3],
"INP": [3, 1],
"OUT": [4, 1],
"BNZ": [5, 2],
"BRZ": [6, 2],
"TLT": [7, 3],
"TEQ": [8, 3],
"REL": [9,1],
"HALT": [99, 0],
}
program_tape: List[int] = []
print(
"Enter instructions, on individual lines, followed by a trailing newline"
" to end your code. Any line beginning with a # character will be ignored."
)
for instruction in iter(input, ""):
if instruction.startswith("#"):
continue
opcode, *params = instruction.split(" ")
if opcode != "DAT":
if opcode not in MNEMONICS:
print("Invalid opcode:", opcode)
exit()
value, param_length = MNEMONICS[opcode]
if len(params) != param_length:
print(
"Too {} parameters for {}; {} expected but {} given".format(
"many" if len(params) > param_length else "few",
opcode,
param_length,
len(params),
)
)
exit()
new_params: List[int] = []
for param_no, param in enumerate(params):
if opcode != "DAT":
if param.startswith("#"):
value += 10 ** (param_no + 2)
param = param[1:]
base = 10
if param.startswith("$"):
base = 16
param = param[1:]
new_params.append(int(param, base))
if opcode != "DAT":
program_tape.append(value)
program_tape.extend(new_params)
print(",".join(map(str, program_tape)))