retyped day2, completed days 3 and 4, modified template

This commit is contained in:
2024-12-01 16:19:37 +01:00
parent 42bab0cb9e
commit 9e21d8d9c8
12 changed files with 134 additions and 26 deletions

29
day4/common.py Normal file
View File

@@ -0,0 +1,29 @@
from __future__ import annotations
import re
from typing import NamedTuple
class Range(NamedTuple):
first: int
last: int
def __contains__(self, other: Range) -> bool:
return self.first <= other.first and self.last >= other.last
def __str__(self):
return f"{self.first}-{self.last}"
def overlaps_with(self, other: Range) -> bool:
return Range(other.first, other.first) in self or Range(other.last, other.last) in self
def parse(filename: str) -> list[tuple[Range, Range]]:
pairs = []
with open(filename) as f:
while line := f.readline():
if match := re.match(r"(\d+)-(\d+),(\d+)-(\d+)", line):
pairs.append(
(Range(int(match.group(1)), int(match.group(2))), Range(int(match.group(3)), int(match.group(4))))
)
return pairs

13
day4/part1.py Normal file
View File

@@ -0,0 +1,13 @@
from common import Range, parse
def solve(input: list[tuple[Range, Range]]) -> int:
return len(list(filter(lambda x: x[0] in x[1] or x[1] in x[0], input)))
def main():
print(solve(parse("input")))
if __name__ == "__main__":
main()

13
day4/part2.py Normal file
View File

@@ -0,0 +1,13 @@
from common import Range, parse
def solve(input: list[tuple[Range, Range]]) -> int:
return len(list(filter(lambda x: x[0].overlaps_with(x[1]) or x[1].overlaps_with(x[0]), input)))
def main():
print(solve(parse("input")))
if __name__ == "__main__":
main()

6
day4/toy_input Normal file
View File

@@ -0,0 +1,6 @@
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8