aoc2021/day10.py
Stefan Harmuth 4a8b06b141 day10
2021-12-10 06:40:18 +01:00

53 lines
1.3 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):
test_solutions_p1 = [26397]
test_solutions_p2 = [288957]
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]