From 64a9220b62976636f012e4b1e2e6ac8cbde9827e Mon Sep 17 00:00:00 2001 From: Tom van der Lee Date: Sat, 3 Dec 2022 18:03:54 +0100 Subject: Day 3 --- day3/__init__.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 day3/__init__.py (limited to 'day3/__init__.py') diff --git a/day3/__init__.py b/day3/__init__.py new file mode 100644 index 0000000..a9e1506 --- /dev/null +++ b/day3/__init__.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +from abc import ABC +from typing import Iterator, Any, List, Tuple + +from aoc import BaseAssignment + + +class Assignment(BaseAssignment, ABC): + def calculate_priority(self, item: str) -> int: + ascii_nr = ord(item) + + if ascii_nr >= 97: + return ascii_nr - 96 + + return ascii_nr - 38 + + +class AssignmentOne(Assignment): + example_result = 157 + + def split_rucksack(self, rucksack: str) -> Tuple[str, str]: + half = len(rucksack) // 2 + return rucksack[:half], rucksack[half:] + + def find_common(self, rucksack: str) -> str: + compartment_one, compartment_two = self.split_rucksack(rucksack) + overlapping = set(compartment_one).intersection(compartment_two) + + return overlapping.pop() + + def run(self, input: Iterator) -> Any: + return sum( + [ + self.calculate_priority(self.find_common(rucksack=rucksack)) + for rucksack in input + ] + ) + + +class AssignmentTwo(Assignment): + example_result = 70 + + def run(self, input: Iterator) -> Any: + prioritisation = [] + + while True: + try: + rucksack_1 = set(next(input)) + rucksack_2 = set(next(input)) + rucksack_3 = set(next(input)) + + prioritisation.append( + self.calculate_priority( + rucksack_1.intersection(rucksack_2, rucksack_3).pop() + ) + ) + except StopIteration: + break + + return sum(prioritisation) -- cgit v1.2.3