• # En Python

    Posté par (site web personnel) . En réponse au message Avent du Code, jour 4. Évalué à 4.

    En Python, en utilisant une classe dédiée (je trouve que ça se lit mieux ainsi) :

    from typing import Iterable, Tuple
    import aoc
    class Interval:
     """An interval of integers"""
     def __init__(self, start: int, end: int):
     """Create a new interval of integers, from start to end included"""
     self.start = start
     self.end = end
     def includes(self, other):
     """Does this interval include the other one?"""
     return self.start <= other.start and self.end >= other.end
     def overlaps(self, other):
     """Does this interval overlap the other one?"""
     return self.end >= other.start and self.start <= other.end
    def import_interval(s: str) -> Interval:
     """Import an interval from a string such as "2-4" """
     part1, part2 = s.split('-')
     return Interval(int(part1), int(part2))
    def import_pairs(lines: Iterable[str]) -> Iterable[Tuple[Interval, Interval]]:
     """Import a pair of intervals from a line such as "2-4,5-8\\n" """
     for line in lines:
     part1, part2 = line.rstrip().split(',')
     yield import_interval(part1), import_interval(part2)
    def solve_both(lines: Iterable[str]) -> Tuple[int, int]:
     """Solve both parts of today's puzzle"""
     inclusions = 0
     overlaps = 0
     for a1, a2 in import_pairs(lines):
     if a1.includes(a2) or a2.includes(a1):
     inclusions += 1
     if a1.overlaps(a2):
     overlaps += 1
     return inclusions, overlaps