From bf6881bacb3d8521f10e4e0589a68d2025dd0d56 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Fri, 10 Dec 2021 13:24:45 +0100 Subject: [PATCH] 2021: d10: ex2: add solution --- 2021/d10/ex2/ex2.py | 81 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100755 2021/d10/ex2/ex2.py diff --git a/2021/d10/ex2/ex2.py b/2021/d10/ex2/ex2.py new file mode 100755 index 0000000..d100b0f --- /dev/null +++ b/2021/d10/ex2/ex2.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python + +import sys +from typing import Iterator, List, Optional + + +def solve(input: List[str]) -> int: + def find_illegal_char(input: str) -> Optional[int]: + chunks: List[str] = [] + ends_to_start = { + ")": "(", + "]": "[", + "}": "{", + ">": "<", + } + + for i, c in enumerate(input): + # Is it a chunk beginning + if c not in ends_to_start: + chunks.append(c) + continue + # Is it matching the last element on the chunk stack + current = chunks.pop() + # If not, corruption has been found + if ends_to_start[c] != current: + return i + + return None + + def complete_line(input: str) -> str: + chunks: List[str] = [] + start_to_end = { + "(": ")", + "[": "]", + "{": "}", + "<": ">", + } + + for c in input: + # Is it a chunk beginning + if c in start_to_end: + chunks.append(c) + continue + # Otherwise we must match the last open chunk + assert start_to_end[chunks.pop()] == c # Sanity check + + return "".join(reversed(list(start_to_end[c] for c in chunks))) + + def score_completion(completion: str) -> int: + char_score = { + ")": 1, + "]": 2, + "}": 3, + ">": 4, + } + + score = 0 + + for c in completion: + score *= 5 + score += char_score[c] + + return score + + def score_completions(completions: Iterator[str]) -> int: + scores = sorted(map(score_completion, completions)) + return scores[len(scores) // 2] + + incomplete_lines = filter(lambda line: find_illegal_char(line) is None, input) + completions = map(complete_line, incomplete_lines) + + return score_completions(completions) + + +def main() -> None: + input = [line.strip() for line in sys.stdin.readlines()] + print(solve(input)) + + +if __name__ == "__main__": + main()