summaryrefslogtreecommitdiffstats
path: root/day3/__init__.py
blob: a9e15066241058af999ff16ff12f55b437655e32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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)