aoc2022/d4.py
2023-12-03 18:44:22 -05:00

65 lines
1.4 KiB
Python

import re
from string import ascii_lowercase, ascii_uppercase
EXAMPLE = """
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
"""
def clean(text: str) -> list[str]:
return list(filter(lambda l: l.strip() != "", text.splitlines()))
def solve(lines: list[str]):
s = 0
for (i, line) in enumerate(lines):
s1, s2 = line.split(',')
a, b = s1.split('-')
c, d = s2.split('-')
a = int(a)
b = int(b)
c = int(c)
d = int(d)
a = set(list(range(a, b + 1)))
b = set(list(range(c, d + 1)))
if a <= b or b <= a:
s += 1
return s
def solve2(lines: list[str]):
s = 0
for (i, line) in enumerate(lines):
s1, s2 = line.split(',')
a, b = s1.split('-')
c, d = s2.split('-')
a = int(a)
b = int(b)
c = int(c)
d = int(d)
a = set(list(range(a, b + 1)))
b = set(list(range(c, d + 1)))
c = a.intersection(b)
if c:
s += 1
# 7:08
return s
def main():
example = clean(EXAMPLE)
print("Example 1:", solve(example))
data = clean(open("i4.txt").read())
print("Solution 1:", solve(data))
example = clean(EXAMPLE)
print("Example 2:", solve2(example))
data = clean(open("i4.txt").read())
print("Solution 2:", solve2(data))
if __name__ == "__main__":
main()