Day 4 – Cleaning Up The Landing Zone
The Problem Part 1:
Space needs to be cleared before the last supplies can be unloaded from the ships, and so several Elves have been assigned the job of cleaning up sections of the camp. Every section has a unique ID number, and each Elf is assigned a range of section IDs.
However, as some of the Elves compare their section assignments with each other, they’ve noticed that many of the assignments overlap. To try to quickly find overlaps and reduce duplicated effort, the Elves pair up and make a big list of the section assignments for each pair (your puzzle input).
Some of the pairs have noticed that one of their assignments fully contains the other. For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6. In pairs where one assignment fully contains the other, one Elf in the pair would be exclusively cleaning sections their partner will already be cleaning, so these seem like the most in need of reconsideration. In this example, there are 2 such pairs.
In how many assignment pairs does one range fully contain the other?
The Problem Part 2:
It seems like there is still quite a bit of duplicate work planned. Instead, the Elves would like to know the number of pairs that overlap at all.
These two problems use two seperate functions, but the same loop to solve both at once. I’m particularly proud of my solution for checking on Overlap, though I’m not sure if it’s the best solution. For example, with the sample data:
2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8
the first one 2-4, and 6-8, does not over lap at all, but in the 4th one, 2-8 completely contains 3-7. What I used was simple math based logic, substrct the start numbers and end numbers. With the lines 1 and 4, this would give:
2-6 = -4, 4-8 = -4 2-3 = -1, 8-7 = 1
Then, multiply each of these results together for each elf.
-4 * -4 = 16 -1 * 1 = -1
For all lines, if the result is greater than 0, it’s not 100% inclusive. From the above, 16, is not, -1 is. This is also true of line 5, which will result in 0. A zero results if either the start or end are equal, which will always be completely inclusive.
with open("Day04Input.txt") as file: data = file.read() worklist = data.split("\n") def check_range(elves): work = elves.split(",") elf1 = work.split("-") elf2 = work.split("-") for i in range(int(elf1),int(elf1)+1): if i in range(int(elf2),int(elf2)+1): return 1 return 0 def check_overlap(elves): work = elves.split(",") elf1 = work.split("-") elf2 = work.split("-") if (int(elf1)-int(elf2))*(int(elf1)-int(elf2)) > 0: return 0 return 1 total = 0 range_total = 0 for each in worklist: total += check_overlap(each) range_total += check_range(each) print(total) #485 print(range_total) # 658 LOW #857
Josh Miller aka “Ramen Junkie”. I write about my various hobbies here. Mostly coding, photography, and music. Sometimes I just write about life in general. I also post sometimes about toy collecting and video games at Lameazoid.com.