This repository was archived by the owner on Nov 12, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart1.py
86 lines (66 loc) · 1.76 KB
/
part1.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
from __future__ import annotations
import argparse
import collections
import os.path
import support
INPUT_TXT = os.path.join(os.path.dirname(__file__), 'input.txt')
TOGGLE = {
'inc': 'dec',
'dec': 'inc',
'tgl': 'inc',
'jnz': 'cpy',
'cpy': 'jnz',
}
def compute(s: str) -> int:
regs: dict[str, int] = collections.defaultdict(int)
regs['a'] = 7
def _lookup(s: str) -> int:
if s.isalpha():
return regs[s]
else:
return int(s)
instructions = [line.split() for line in s.splitlines()]
pc = 0
while 0 <= pc < len(instructions):
match instructions[pc]:
case 'cpy', src, dest:
if dest.isalpha():
regs[dest] = _lookup(src)
pc += 1
case 'inc', dest:
regs[dest] += 1
pc += 1
case 'dec', dest:
regs[dest] -= 1
pc += 1
case 'jnz', cond, jump:
if _lookup(cond):
pc += _lookup(jump)
else:
pc += 1
case 'tgl', dest:
target = pc + _lookup(dest)
if 0 <= target < len(instructions):
instructions[target][0] = TOGGLE[instructions[target][0]]
pc += 1
return regs['a']
EXAMPLE = '''\
cpy 2 a
tgl a
tgl a
tgl a
cpy 1 a
dec a
dec a
'''
def test() -> None:
assert compute(EXAMPLE) == 3
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('data_file', nargs='?', default=INPUT_TXT)
args = parser.parse_args()
with open(args.data_file) as f, support.timing():
print(compute(f.read()))
return 0
if __name__ == '__main__':
raise SystemExit(main())