« posts | «« home

Day 4: Camp Cleanup

View puzzle page »

Skip to the code?

If you’d like to read my solution first, the code is available on GitHub.

Puzzle 1

In this puzzle, the task is to identify when, in a pair of a range of numbers, one range fully contains the other, e.g. 2-4 is contained in 1-5.

Put differently: if the start of one pair is equal to or less than the start of the other pair and the end of the first pair is equal to or greater than the end of the other pair, add one to your count.


First thing’s first, we need to loop the pairs, do some formatting, and get our pairs into objects.

with open("day4_input.txt", encoding="utf-8") as f:
    for line in f.readlines():
        pair1, pair2 = line.split(',')
        start1, end1 = pair1.split('-')
        start2, end2 = pair2.split('-')

We split the pairs from each other by comma (from 75-76,18-75 to ['75-76','18-75']) and then from themselves by dash (from '75-76' to ['75','76']).

Then we need to coerce all the values to integers to ensure our boolean logic works correctly. We use a list comprehension to read in the variables, coerce with int, and store back to the same variables.

start1, start2, end1, end2 = [int(x) for x in [start1, start2, end1, end2]]

Now we can evaluate the pairs with an if statement. We need to compare the start values of both pairs with each other and, in the case that either is less than its counterpart, we evaluate the end values to determine whether one fully contains the other.

if (start1 <= start2 and end2 <= end1) \
    or (start2 <= start1 and end1 <= end2):
        count_pairs += 1

We add to the count when the conditional passes and the total is our answer to puzzle 1.

Puzzle 2

As might have been expected, puzzle 2 requires figuring out all cases when there is any overlap in the pairs.


Our code remains largely the same but we’re solving a distinctly easier problem.

if end1 >= start2 and end2 >= start1:
    count_pairs += 1

We count any case where the end value of one pair is greater the start value of the second pair while the end value of the second pair is also greater than the start value of the first pair. We sum the count and that gives us our answer for puzzle 2.

Source Code

View the code on GitHub.

Would you like to read something else by me?

« «

» »

« posts | «« home