Ho, ho, ho, Happy Chris.. New Year? Between eating the sea of fish (as the Polish tradition requires), assembling doll houses and designing a new kitchen, I finally managed to publish the third post on My R take on Advent of Code. To keep things short and sweet, here’s the original challenge:
Each Elf has made a claim about which area of fabric would be ideal for Santa’s suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim’s rectangle is defined as follows:The number of inches between the left edge of the fabric and the left edge of the rectangle.The number of inches between the top edge of the fabric and the top edge of the rectangle.The width of the rectangle in inches.The height of the rectangle in inches.A claim like #123 @ 3,2: 5×4 means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. Visually, it claims the square inches of fabric represented by # (and ignores the square inches of fabric represented by .) in the diagram below:
………..………..…#####……#####……#####……#####…………..………..………..
The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
#1 @ 1,3: 4×4#2 @ 3,1: 4×4#3 @ 5,5: 2×2
Visually, these claim the following areas:
……..…2222.…2222..11XX22..11XX22..111133..111133.……..
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.). If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
This is interesting! let’s load tidyverse
and have a quick look at the data:
1 |
|
1 |
|
Ha! It looks like we need to first extract each dimension from the original input – easy-peasy with a little bit of regex and parse_number
:
1 |
|
1 |
|
Now that we have the dimensions, how do we go about determining the overlap?My idea was to, for each claim, create a series of ‘coordinates’ where the digit before a dot indicates the position from the left edge and the second number the position from the top edge. Overlapping squares from different samples would have the same ‘coordinates’.
Right, but how to do it in R? this is where outer
function comes in handy. Let’s take the first example:
1 |
|
1 |
|
Neat! Now, let’s wrap it up in a function and apply it to the challenge dataset:
1 |
|
1 |
|
Now, let’s calculate the number of those coordiates that appear more than once in our list, which will give us the final solution to the Day 3 Puzzle:
1 |
|
1 |
|
Related