-
Notifications
You must be signed in to change notification settings - Fork 0
/
part_a.py
executable file
·218 lines (176 loc) · 6.64 KB
/
part_a.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python3
import re
import utils
class Challenge(utils.BaseChallenge):
def solve(self, _input, debug=False):
"""
>>> Challenge().default_solve()
9879607673316
"""
return Program.from_program_text(_input).run_and_get_memory_checksum()
class Program:
instruction_class = NotImplemented
@classmethod
def from_program_text(cls, program_text):
"""
>>> Program.from_program_text(
... "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X\\n"
... "mem[8] = 11\\n"
... "mem[7] = 101\\n"
... "mem[8] = 0\\n"
... ).instructions
[Bitmask(66, 64), Write(8, 11), Write(7, 101), Write(8, 0)]
"""
non_empty_lines = filter(None, program_text.splitlines())
return cls(list(map(cls.instruction_class.parse, non_empty_lines)))
def __init__(self, instructions):
self.instructions = instructions
def run_and_get_memory_checksum(self, memory=None):
"""
>>> Program.from_program_text(
... "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X\\n"
... "mem[8] = 11\\n"
... "mem[7] = 101\\n"
... "mem[8] = 0\\n"
... ).run_and_get_memory_checksum()
165
"""
memory = self.run(memory)
return self.get_memory_checksum(memory)
def run(self, memory=None):
"""
>>> Program([]).run()
{'bitmask': 0, 'override': 0, 'values': {}}
>>> Program.from_program_text(
... "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X\\n"
... "mem[8] = 11\\n"
... "mem[7] = 101\\n"
... "mem[8] = 0\\n"
... ).run()
{'bitmask': 66, 'override': 64, 'values': {8: 64, 7: 101}}
"""
if memory is None:
memory = self.get_default_memory()
for instruction in self.instructions:
instruction.step(memory)
return memory
def get_default_memory(self):
return {'bitmask': 0, 'override': 0, 'values': {}}
def get_memory_checksum(self, memory):
"""
>>> Program([]).get_memory_checksum(
... {'bitmask': 66, 'override': 64, 'values': {8: 64, 7: 101}})
165
"""
return sum(memory['values'].values())
class Instruction:
name = NotImplemented
instruction_classes = {}
@classmethod
def register(cls, instruction_class, override=False):
if instruction_class.name is NotImplemented:
raise Exception(
f"Instruction {instruction_class.__name__} didn't specify "
f"name")
if instruction_class.name in cls.instruction_classes and not override:
raise Exception(
f"Instruction {instruction_class.__name__} tried to "
f"implicitly override {instruction_class.name}, that was "
f"already defined by "
f"{cls.instruction_classes[instruction_class.name].__name__}")
cls.instruction_classes[instruction_class.name] = instruction_class
return instruction_class
@classmethod
def parse(cls, instruction_text):
for instruction_class in cls.instruction_classes.values():
instruction = instruction_class.try_parse(instruction_text)
if instruction:
return instruction
raise Exception(f"Could not parse '{instruction_text}'")
@classmethod
def try_parse(cls, instruction_text):
raise NotImplementedError()
def step(self, memory):
raise NotImplementedError()
Program.instruction_class = Instruction
@Instruction.register
class Write(Instruction):
name = 'write'
re_write = re.compile(r"^mem\[(\d+)] = (\d+)$")
@classmethod
def try_parse(cls, instruction_text):
"""
>>> Write\\
... .try_parse("mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X")
>>> Write\\
... .try_parse("mem[8] = 11")
Write(8, 11)
"""
match = cls.re_write.match(instruction_text)
if not match:
return None
address_str, value_str = match.groups()
return cls(int(address_str), int(value_str))
def __init__(self, address, value):
self.address = address
self.value = value
def __repr__(self):
return f"{type(self).__name__}({self.address}, {self.value})"
def step(self, memory):
"""
>>> Write(8, 11).step({'bitmask': 0, 'override': 0, 'values': {}})
{'bitmask': 0, 'override': 0, 'values': {8: 11}}
>>> Write(8, 11).step({'bitmask': 66, 'override': 64, 'values': {}})
{'bitmask': 66, 'override': 64, 'values': {8: 73}}
>>> Write(8, 127).step({'bitmask': 66, 'override': 64, 'values': {}})
{'bitmask': 66, 'override': 64, 'values': {8: 125}}
>>> Write(8, 11)\\
... .step({'bitmask': 0, 'override': 0, 'values': {8: 10, 9: 32}})
{'bitmask': 0, 'override': 0, 'values': {8: 11, 9: 32}}
>>> Write(8, 0)\\
... .step({'bitmask': 0, 'override': 0, 'values': {8: 10, 9: 32}})
{'bitmask': 0, 'override': 0, 'values': {9: 32}}
"""
bitmask = memory['bitmask']
override = memory['override']
masked_value = (self.value & ~bitmask) | override
memory['values'][self.address] = masked_value
if masked_value == 0:
del memory['values'][self.address]
return memory
@Instruction.register
class Bitmask(Instruction):
name = 'bitmask'
re_bitmask = re.compile(r"^mask = ([01X]{36})$")
@classmethod
def try_parse(cls, instruction_text):
"""
>>> Bitmask\\
... .try_parse("mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X")
Bitmask(66, 64)
>>> Bitmask\\
... .try_parse("mem[8] = 11")
"""
match = cls.re_bitmask.match(instruction_text)
if not match:
return None
bitmask_str, = match.groups()
bitmask = int(bitmask_str.replace('0', '1').replace('X', '0'), 2)
override = int(bitmask_str.replace('X', '0'), 2)
return cls(bitmask, override)
def __init__(self, bitmask, override):
self.bitmask = bitmask
self.override = override
def __repr__(self):
return f"{type(self).__name__}({self.bitmask}, {self.override})"
def step(self, memory):
"""
>>> Bitmask(66, 64)\\
... .step({'bitmask': 0, 'override': 0, 'values': {8: 11}})
{'bitmask': 66, 'override': 64, 'values': {8: 11}}
"""
memory['bitmask'] = self.bitmask
memory['override'] = self.override
return memory
Challenge.main()
challenge = Challenge()