-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaoc201718.py
154 lines (120 loc) · 4.12 KB
/
aoc201718.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
"""AoC 18, 2017: Duet."""
# Standard library imports
import collections
import pathlib
import sys
from dataclasses import dataclass
def parse_data(puzzle_input):
"""Parse input."""
return [parse_instruction(line) for line in puzzle_input.split("\n")]
def parse_instruction(line):
"""Parse one instruction.
## Examples:
>>> parse_instruction("snd g")
('snd', 'g')
>>> parse_instruction("set g 45")
('set', 'g', 45)
>>> parse_instruction("mul z a")
('mul', 'z', 'a')
"""
instruction, register, *args = line.split()
return instruction, try_int(register), *[try_int(arg) for arg in args]
def try_int(maybe_number):
"""Convert to int if possible.
## Examples:
>>> try_int("42")
42
>>> try_int("g")
'g'
"""
try:
return int(maybe_number)
except ValueError:
return maybe_number
def part1(instructions):
"""Solve part 1."""
program = Program(instructions, play_sound=True)
while True:
status = program.step()
if status != "running":
return program.last_sound_played
def part2(instructions):
"""Solve part 2."""
queue_0, queue_1 = collections.deque(), collections.deque()
program_0 = Program(instructions, program_id=0, queue=queue_0, other=queue_1)
program_1 = Program(instructions, program_id=1, queue=queue_1, other=queue_0)
while True:
status_0, status_1 = program_0.step(), program_1.step()
if status_0 != "running" and status_1 != "running":
return program_1.num_messages_sent
class Registers(collections.UserDict):
"""Dictionary with special handling of missing keys."""
def __missing__(self, key):
"""Pass through integer keys. Otherwise default to 0.
## Examples:
>>> Registers({"p": 1})["p"]
1
>>> Registers({"p": 1})["q"]
0
>>> Registers({"p": 1})[14]
14
"""
if isinstance(key, int):
return key
self.data[key] = 0
return 0
@dataclass
class Program:
"""A program that can be run."""
instructions: list[tuple[str, str, int]]
program_id: int = 0
queue: collections.deque = None
other: collections.deque = None
play_sound: bool = False
pointer: int = 0
num_messages_sent: int = 0
last_sound_played: int = 0
def __post_init__(self):
"""Set up registers."""
self.num_instructions = len(self.instructions)
self.registers = Registers({"p": self.program_id})
def step(self):
"""Run one step of the program."""
if self.pointer < 0 or self.pointer >= self.num_instructions:
return "terminated"
instruction, register, *args = self.instructions[self.pointer]
value = self.registers[args[0]] if args else 0
if instruction == "snd" and self.play_sound:
self.last_sound_played = self.registers[register]
elif instruction == "snd":
self.num_messages_sent += 1
self.other.append(self.registers[register])
elif instruction == "set":
self.registers[register] = value
elif instruction == "add":
self.registers[register] += value
elif instruction == "mul":
self.registers[register] *= value
elif instruction == "mod":
self.registers[register] %= value
elif instruction == "rcv" and self.play_sound:
return "terminated"
elif instruction == "rcv":
if self.queue:
self.registers[register] = self.queue.popleft()
else:
return "waiting"
elif instruction == "jgz" and self.registers[register] > 0:
self.pointer += value - 1
self.pointer += 1
return "running"
def solve(puzzle_input):
"""Solve the puzzle for the given input."""
data = parse_data(puzzle_input)
yield part1(data)
yield part2(data)
if __name__ == "__main__":
for path in sys.argv[1:]:
print(f"\n{path}:")
solutions = solve(puzzle_input=pathlib.Path(path).read_text().rstrip())
print("\n".join(str(solution) for solution in solutions))