« posts | «« home

# Day 4: Camp Cleanup

View puzzle page »

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.

### Solution

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

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.

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.

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.

### Solution

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

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