diff options
| author | 2022-12-03 18:03:54 +0100 | |
|---|---|---|
| committer | 2022-12-03 18:03:54 +0100 | |
| commit | 64a9220b62976636f012e4b1e2e6ac8cbde9827e (patch) | |
| tree | a6e42102456356d76dae73cba27126dab82a884c /day3/__init__.py | |
| parent | cf4757ad43823aafa4c6c0547265359e961245a8 (diff) | |
| download | 2022-64a9220b62976636f012e4b1e2e6ac8cbde9827e.tar.gz 2022-64a9220b62976636f012e4b1e2e6ac8cbde9827e.tar.bz2 2022-64a9220b62976636f012e4b1e2e6ac8cbde9827e.zip | |
Day 3
Diffstat (limited to 'day3/__init__.py')
| -rw-r--r-- | day3/__init__.py | 60 |
1 files changed, 60 insertions, 0 deletions
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 @@ | |||
| 1 | # -*- coding: utf-8 -*- | ||
| 2 | from abc import ABC | ||
| 3 | from typing import Iterator, Any, List, Tuple | ||
| 4 | |||
| 5 | from aoc import BaseAssignment | ||
| 6 | |||
| 7 | |||
| 8 | class Assignment(BaseAssignment, ABC): | ||
| 9 | def calculate_priority(self, item: str) -> int: | ||
| 10 | ascii_nr = ord(item) | ||
| 11 | |||
| 12 | if ascii_nr >= 97: | ||
| 13 | return ascii_nr - 96 | ||
| 14 | |||
| 15 | return ascii_nr - 38 | ||
| 16 | |||
| 17 | |||
| 18 | class AssignmentOne(Assignment): | ||
| 19 | example_result = 157 | ||
| 20 | |||
| 21 | def split_rucksack(self, rucksack: str) -> Tuple[str, str]: | ||
| 22 | half = len(rucksack) // 2 | ||
| 23 | return rucksack[:half], rucksack[half:] | ||
| 24 | |||
| 25 | def find_common(self, rucksack: str) -> str: | ||
| 26 | compartment_one, compartment_two = self.split_rucksack(rucksack) | ||
| 27 | overlapping = set(compartment_one).intersection(compartment_two) | ||
| 28 | |||
| 29 | return overlapping.pop() | ||
| 30 | |||
| 31 | def run(self, input: Iterator) -> Any: | ||
| 32 | return sum( | ||
| 33 | [ | ||
| 34 | self.calculate_priority(self.find_common(rucksack=rucksack)) | ||
| 35 | for rucksack in input | ||
| 36 | ] | ||
| 37 | ) | ||
| 38 | |||
| 39 | |||
| 40 | class AssignmentTwo(Assignment): | ||
| 41 | example_result = 70 | ||
| 42 | |||
| 43 | def run(self, input: Iterator) -> Any: | ||
| 44 | prioritisation = [] | ||
| 45 | |||
| 46 | while True: | ||
| 47 | try: | ||
| 48 | rucksack_1 = set(next(input)) | ||
| 49 | rucksack_2 = set(next(input)) | ||
| 50 | rucksack_3 = set(next(input)) | ||
| 51 | |||
| 52 | prioritisation.append( | ||
| 53 | self.calculate_priority( | ||
| 54 | rucksack_1.intersection(rucksack_2, rucksack_3).pop() | ||
| 55 | ) | ||
| 56 | ) | ||
| 57 | except StopIteration: | ||
| 58 | break | ||
| 59 | |||
| 60 | return sum(prioritisation) | ||
