aoc2021/day10.py
2021-12-28 10:05:13 +01:00

66 lines
1.5 KiB
Python

from tools.aoc import AOCDay
from typing import Any, List
PAIRS = {
"<": ">",
"(": ")",
"{": "}",
"[": "]"
}
def parse_line(line: str) -> (bool, List[str], str): # (corrupt, expected_closings, last_char)
expect_close = []
for c in line:
if c in PAIRS:
expect_close.insert(0, PAIRS[c])
else:
if c != expect_close.pop(0):
return True, expect_close, c
return False, expect_close, ""
class Day(AOCDay):
inputs = [
[
(26397, "test_input10"),
(168417, "input10")
],
[
(288957, "test_input10"),
(2802519786, "input10")
]
]
def part1(self) -> Any:
char_scores = {")": 3, "]": 57, "}": 1197, ">": 25137}
total_score = 0
for line in self.getInput():
corrupt, _, c = parse_line(line)
if corrupt:
total_score += char_scores[c]
return total_score
def part2(self) -> Any:
scores = []
for line in self.getInput():
corrupt, expect_close, _ = parse_line(line)
if not corrupt and len(expect_close) > 0:
line_score = 0
for c in expect_close:
line_score *= 5
line_score += [")", "]", "}", ">"].index(c) + 1
scores.append(line_score)
return list(sorted(scores))[len(scores) // 2]
if __name__ == '__main__':
day = Day(2021, 10)
day.run(verbose=True)