Sean McLemon | Advent of Code

Home | Czech | Blog | GitHub | Advent Of Code | Notes


2022-12-04 - Camp Cleanup

(original .ipynb)

Day 4 puzzle input is a list of pairs of ranges which represent which sections a given elf is assigned to clean (mine is here). Part 1 involves finding how many elves were given a pair of section assignments where one assignment completely contains the other. Part 2 involves finding how many elves simply have overlapping assignments.

puzzle_input_str = open("./puzzle_input/day4.txt").read()

test_input_str = """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 parse_range(range_str):
    start, end = range_str.split("-")
    return int(start), int(end)


def parse_assignment(line):
    first, second = line.split(",")
    return parse_range(first), parse_range(second)


def contains(assignment1, assignment2):
    s1, e1 = assignment1
    s2, e2 = assignment2
    return s1 <= s2 and e1 >= e2


def part_one(input_str):
    assignments = [parse_assignment(line) for line in input_str.splitlines()]
    return sum(1 for first, second in assignments if contains(first, second) or contains(second, first))


assert 2 == part_one(test_input_str)

print("part one:", part_one(puzzle_input_str))
part one: 571
def overlaps(assignment1, assignment2):
    s1, e1 = assignment1
    s2, e2 = assignment2
    return (s1 >= s2 and s1 <= e2) or (e1 >= s2 and e1 <= e2)


def part_two(input_str):
    assignments = [parse_assignment(line) for line in input_str.splitlines()]
    return sum(1 for first, second in assignments if overlaps(first, second) or overlaps(second, first))


assert 4 == part_two(test_input_str)

print("part two:", part_two(puzzle_input_str))
part two: 917