From 2b9aa841932eee67ea08463fa9aff940c1865df5 Mon Sep 17 00:00:00 2001 From: Ryan Reed Date: Fri, 10 Dec 2021 20:59:54 -0500 Subject: [PATCH] Adding Day 10 Part 2 --- puzzles/day10.py | 30 ++++++++++++++++++++++++------ tests/test_day10.py | 6 ++---- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/puzzles/day10.py b/puzzles/day10.py index b1ba859..7df9b1f 100644 --- a/puzzles/day10.py +++ b/puzzles/day10.py @@ -9,7 +9,7 @@ import pathlib import sys from typing import Dict, List, Tuple -from collections import Counter +from statistics import median @@ -18,13 +18,14 @@ class Subsystem: open_chars = ['(', '[', '{', '<'] close_chars = [')', ']', '}', '>'] - def __init__(self, inputs): + def __init__(self, inputs: List[str]) -> None: self.nav_data = inputs - self.chunks, self.corrupted_chars = self.validate() + self.validate() - def validate(self) -> Tuple[Dict, List[str]]: + def validate(self) -> None: chunks = {"corrupted": [], "incomplete": [], "complete": []} corrupted_chars = [] + incomplete_chunks = [] for line in self.nav_data: corrupted = False @@ -47,15 +48,31 @@ class Subsystem: chunks["corrupted"].append(line) elif len(opens) != 0: chunks["incomplete"].append(line) + incomplete_chunks.append(opens) else: chunks["complete"].append(line) - return chunks, corrupted_chars + self.chunks = chunks + self.corrupted_chars = corrupted_chars + self.incomplete_chunks = incomplete_chunks def score_corrupted(self) -> int: scores = {")": 3, "]": 57, "}": 1197, ">": 25137,} return sum([scores[char] for char in self.corrupted_chars]) + def score_incomplete(self) -> int: + scores = {")": 1, "]": 2, "}": 3, ">": 4,} + total_scores = [] + for chunk in self.incomplete_chunks: + total_score = 0 + for char in reversed(chunk): + close_char = self.close_chars[self.open_chars.index(char)] + total_score = total_score * 5 + scores[close_char] + total_scores.append(total_score) + + return median(total_scores) + + def part1(inputs: List[int]) -> int: s = Subsystem(inputs) @@ -63,7 +80,8 @@ def part1(inputs: List[int]) -> int: def part2(inputs: List[int]) -> int: - return False + s = Subsystem(inputs) + return s.score_incomplete() def parse(inputs: str) -> List[int]: diff --git a/tests/test_day10.py b/tests/test_day10.py index 39824ee..81acba1 100644 --- a/tests/test_day10.py +++ b/tests/test_day10.py @@ -24,15 +24,13 @@ def test_example1(example_data): assert aoc.part1(example_data) == 26397 -@pytest.mark.skip(reason="Not implemented") def test_example2(example_data): - assert aoc.part2(example_data) == ... + assert aoc.part2(example_data) == 288957 def test_part1(day10_data): assert aoc.part1(day10_data) == 387363 -@pytest.mark.skip(reason="Not implemented") def test_part2(day10_data): - assert aoc.part2(day10_data) == ... + assert aoc.part2(day10_data) == 4330777059