Files
advent-of-code-2022/03/py/solution.py
Adrian Rumpold aeebed7ec9 Python: Day 3
2022-12-15 08:00:17 +01:00

66 lines
1.5 KiB
Python

from pathlib import Path
from typing import Generator, TypeVar
from collections.abc import Iterable
T = TypeVar("T")
def threes(i: Iterable[T]) -> Generator[tuple[T, T, T], None, None]:
if len(i) % 3 != 0:
raise ValueError()
for idx in range(0, len(i), 3):
yield i[idx], i[idx + 1], i[idx + 2]
def priority(s: str) -> int:
assert len(s) == 1
if "a" <= s <= "z":
return ord(s) - ord("a") + 1
elif "A" <= s <= "Z":
return ord(s) - ord("A") + 27
raise RuntimeError(f"Invalid char: {s}")
def split(s: str) -> tuple[str, str]:
mid = len(s) // 2
return s[:mid], s[mid:]
def part1(data: str) -> int:
result = 0
for line in data.splitlines():
left, right = split(line)
both = {ch for ch in right}.intersection({ch for ch in left})
value = 0
for ch in both:
value += priority(ch)
print(f"{line}: {both}")
result += value
return result
def part2(data: str) -> int:
result = 0
lines = data.splitlines()
for a, b, c in threes(lines):
badge = set(a).intersection(set(b)).intersection(set(c))
value = 0
for ch in badge:
value += priority(ch)
result += value
return result
# Setup
data = (Path(__file__).parents[1] / "input").read_text()
# Problem solving - part 1
result = part1(data)
print(f"Part 1 solution: {result}")
# Problem solving - part 2
result = part2(data)
print(f"Part 2 solution: {result}")