Advent of Code 2022 day 4
Python solution for Advent of Code 2022 day 4. Used ranges
and sets
to do the heavy lifting, which felt like too much work for part 1 but it made part 2 easy as pie.
from unittest import TestCase
from utils import get_raw_input
def build_section_pairs(raw_input):
return [
tuple(
set(range(int(elf.split("-")[0]), int(elf.split("-")[1]) + 1))
for elf in pair.split(",")
)
for pair in raw_input
]
def superset_pair(pair):
if pair[0] >= pair[1] or pair[1] >= pair[0]:
return True
return False
def overlap_pair(pair):
return len(pair[0] & pair[1])
def part_one(raw_input):
return len(list(filter(superset_pair, build_section_pairs(raw_input))))
def part_two(raw_input):
return len(list(filter(overlap_pair, build_section_pairs(raw_input))))
class TestExamples(TestCase):
def setUp(self):
self.assignments = [
"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 test_part_one(self):
self.assertEqual(part_one(self.assignments), 2)
def test_part_two(self):
self.assertEqual(part_two(self.assignments), 4)
if __name__ == "__main__":
raw_input = get_raw_input("day_04_input.txt")
print(f"Part one: {part_one(raw_input)}")
print(f"Part two: {part_two(raw_input)}")