-
Notifications
You must be signed in to change notification settings - Fork 2
/
aoc201805.py
61 lines (46 loc) · 1.46 KB
/
aoc201805.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
"""AoC 5, 2018: Alchemical Reduction."""
# Standard library imports
import pathlib
import sys
# Third party imports
import numpy as np
def parse_data(puzzle_input):
"""Parse input."""
polymer = np.array(
[
ord(letter) - 96 if letter >= "a" else 64 - ord(letter)
for letter in puzzle_input
]
)
return reduce(polymer)
def part1(polymer):
"""Solve part 1."""
return len(polymer)
def part2(polymer):
"""Solve part 2."""
elements = {abs(unit) for unit in polymer}
polymer_lengths = [
len(reduce(polymer[np.abs(polymer) != element])) for element in elements
]
return min(polymer_lengths)
def reduce(polymer):
"""Reduce one polymer as much as possible"""
while True:
reductions = polymer[:-1] + polymer[1:]
if not np.any(reductions == 0):
return polymer
idx, *_ = np.where(reductions == 0)
reduce_idx = idx[np.concatenate(([True], np.diff(idx) != 1))]
polymer[reduce_idx] = 99
polymer[reduce_idx + 1] = 99
polymer = polymer[polymer != 99]
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))