My attempts at the Advent of Code 2022 using R
By Andrew Robson
December 1, 2022
Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like. I’m going to be attempting to solve them in R. Just because I post a solution here doesn’t mean I think it’s the best way to do it, I’m just happy if I’ve got the answer right - we can always optimise later. ☺️
Day 1
Behind day 1’s door is the following problem:
Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?
And a follow up problem:
Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?
We are supplied with an elf meal dataset (your dataset will contain different values to mine) which contains all the information we need - although not in the nicest format. Here is an example of the format, but you will be supplied with a much larger dataset.
Calories |
---|
1000 |
2000 |
3000 |
[BLANK] |
4000 |
[BLANK] |
5000 |
6000 |
The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories. The second Elf is carrying one food item with 4000 Calories. The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories.
I have saved my dataset as a text file called input.txt
. It looks like the main problem here is: how do we wrangle this data into a usable format?
This is my first attempt at a solution. I read in the file as text. Change the blanks into pipes (just so I can see them) then separate over the pipes to get a table with each row representing all the meals a particular elf is carrying. We then give these rows IDs before splitting again, this time putting each individual meal into a new row alongside its new elf_id
.
From there, we can sum up all the meals per elf using summarise
- I’ve decided to add some other summary statistics too for a laugh. Then I sort the rows so we can put the elf who is carrying the most calories at the top - solving problem 1. Once the data is ordered, it’s trivial to slice just the top 3 out - we could then use another summarise to answer problem 2.
library(tidyverse)
myfile <- readLines("input.txt")
myfile %>%
replace(myfile == "", "|") %>%
paste(collapse = " ") %>%
tibble(calories = .) %>%
separate_rows(calories, sep=" \\| ") %>%
mutate(elf_id = row_number()) %>%
group_by(elf_id) %>%
separate_rows(calories, sep = ' ', convert = TRUE) %>%
summarise(calories = sum(calories), meals = n(), avg.meal.size = calories/meals) %>%
arrange(desc(calories)) %>%
slice(1:3)
Okay, so attempt 1 worked fine - why is there an attempt 2?
It just felt really inefficient to be converting blanks to pipes and splitting twice - I felt like there had to be a slightly more streamlined way.
I originally didn’t use read.table
because it was stripping out the blank rows, which are vital to shaping the data. However, on further inspection, there is a parameter to stop it doing that. Let’s set blank.lines.skip
to false. Now, we’re already most of the way there but there is a little bit of manipulating still to do. To get the elf_id
this time I simply cumulatively sum the blank rows and then filter them out - from then on the solution is identical to attempt 1.
library(tidyverse)
read.table("input.txt", blank.lines.skip = F) %>%
mutate(newline = is.na(V1), elf_id = cumsum(newline)) %>%
filter(!is.na(V1)) %>%
select(calories = V1, elf_id) %>%
group_by(elf_id) %>%
summarise(calories = sum(calories), meals = n(), avg.meal.size = calories/meals) %>%
arrange(desc(calories)) %>%
slice(1:3)
Day 2
Today’s problem is all about Rock, Paper, Scissors. We need to win and we have a crib of our opponents moves. We’ve also been told what to play in response, so it doesn’t look to obvious when we win. The data we’re supplied is a whole long list of X, Y, Zs and A, B, Cs. With A, B and C referring to our opponents moves of Rock, Paper or Scissors. We’re also told that the X, Y, Zs are the moves we should make in response, also corresponding to Rock, Paper or Scissors respectively.
It’s 0 points for a loss, 3 points for a draw and 6 points for a win. You also get 1 point for selecting rock, 2 for selecting paper and 3 for scissors. How many points do we get following the strategy we have been given?
I’m not overly happy with today’s solution. It seems really verbose and inefficent but it doest get the right answer. I decided to write a function to calculate the scores from the rock, paper, scissors inputs - this wasn’t really necessary but I thought it might be helpful if part two involved changes to the scoring system. We’ll see if that pays off later.
After writing a function to calculate the scores for winning, I make a lookup table to map the XYZ/ABC to works the function understands and list the scores of each choice. From there, we just join our lookup to our data (twice, once for each player) and run it through the function to get the scores from the games. We add the game scores to the scores for the choice of weapon, add them all up and we’re there.
library(tidyverse)
evaluate_game <- function(player1_input, player2_input){
# Should really validate that the inputs are rock, papper, scissors
draw_points = 3
lose_points = 0
win_points = 6
if(player1_input == player2_input){
return(c(player1_points = draw_points, player2_points = draw_points))
} else if (player1_input == 'Rock' & player2_input == 'Scissors'){
return(c(player1_points = win_points, player2_points = lose_points))
}else if (player1_input == 'Rock' & player2_input == 'Paper'){
return(c(player1_points = lose_points, player2_points = win_points))
}else if (player1_input == 'Paper' & player2_input == 'Rock'){
return(c(player1_points = win_points, player2_points = lose_points))
}else if (player1_input == 'Paper' & player2_input == 'Scissors'){
return(c(player1_points = lose_points, player2_points = win_points))
}else if (player1_input == 'Scissors' & player2_input == 'Rock'){
return(c(player1_points = lose_points, player2_points = win_points))
}else if (player1_input == 'Scissors' & player2_input == 'Paper'){
return(c(player1_points = win_points, player2_points = lose_points))
}
}
look_up <- tibble(Opponent = c('A', 'B', 'C'),
You = c('X', 'Y', 'Z'),
Choice = c('Rock', 'Paper', 'Scissors'),
Points = c(1,2,3))
read.table('AdventData/Day2.txt', header = F) %>%
select(Opponent = V1, You = V2) %>%
left_join(look_up %>% select(You, Choice, Points), by = c("You" = "You")) %>%
left_join(look_up %>% select(Opponent, Choice, Points), by = c("Opponent" = "Opponent")) %>%
select(Your_Choice = Choice.x, Opponent_Choice = Choice.y, Your_Choice_Points = Points.x, Opponent_Choice_Points = Points.y) %>%
rowwise() %>%
mutate(Game_Result = list(evaluate_game(Your_Choice, Opponent_Choice))) %>%
unnest_wider(Game_Result) %>%
mutate(Your_Points = Your_Choice_Points + player1_points, Opponent_Points = Opponent_Choice_Points + player2_points) %>%
select(Your_Choice, Opponent_Choice, Your_Points, Opponent_Points) %>%
summarise(sum(Your_Points))
The follow up problem was not what I was expecting - we’re basically starting again on a new problem. We’re told the X, Y, Z wasn’t actually what we were meant to play but it was the result we were meant to achieve - Lose, Win, Draw. Then based on that, what’s our final score?
Okay, so we no longer need the huge function - a bit of a waste of time. I’ve decided to create a few more lookup tables to solve this new problem. strategy_lookup
maps what we should play when we are given our instruction whether to win, lose or draw. Results look up just converts the X, Y and Z to words we understand for the join. This probably should have been a str_replace_all
.
Carefully left joining our look ups gives us everything we need to sum up our new score.
library(tidyverse)
look_up <- tibble(Opponent = c('A', 'B', 'C'),
You = c('X', 'Y', 'Z'),
Choice = c('Rock', 'Paper', 'Scissors'),
Points = c(1,2,3))
strategy_lookup <- tibble(Play = c('Rock', 'Rock', 'Paper', 'Paper', 'Scissors', 'Scissors'),
Response = c('Paper', 'Scissors', 'Scissors', 'Rock', 'Rock', 'Paper'),
Result = rep(c('Win', 'Lose'), 3))
result_lookup <- tibble(code = c('X', 'Y', 'Z'), Desired_Result = c('Lose', 'Draw', 'Win'), Points = c(0, 3, 6))
read.table('AdventData/Day2.txt', header = F) %>%
select(Opponent = V1, Desired_Result = V2) %>%
left_join(look_up %>% select(Opponent, Choice), by = c("Opponent" = "Opponent")) %>%
left_join(result_lookup, by = c("Desired_Result" = "code")) %>%
select(Opponent_Choice = Choice, Desired_Result = Desired_Result.y, Points) %>%
left_join(strategy_lookup, by = c( "Opponent_Choice" = "Play" , "Desired_Result" = "Result")) %>%
mutate(Response = ifelse(Desired_Result == 'Draw', Opponent_Choice, Response)) %>%
left_join(lookup %>% select(Choice, Points), by = c('Response' = 'Choice')) %>%
mutate(Your_Points = Points.x + Points.y) %>%
summarise(sum(Your_Points))
Day 3
One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn’t quite follow the packing instructions, and so a few items now need to be rearranged.
Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.
The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items).
The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment.
For example, suppose you have the following list of contents from six rucksacks:
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp
, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p.
The second rucksack’s compartments contain jqHRNqRjqzjGDLG
L and rsFMfFZSrLrFZsSL
. The only item type that appears in both compartments is uppercase L.
The third rucksack’s compartments contain PmmdzqPrV
and vPwwTWBwg
; the only common item type is uppercase P.
The fourth rucksack’s compartments only share item type v.
The fifth rucksack’s compartments only share item type t.
The sixth rucksack’s compartments only share item type s.
To help prioritize item rearrangement, every item type can be converted to a priority:
Lowercase item types a through z have priorities 1 through 26.
Uppercase item types A through Z have priorities 27 through 52.
In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.
Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types?
Quite happy with today’s solution. Knowing about R’s letters
and LETTERS
was a big help. The application of set operations also sped things up.
library(tidyverse)
rucksacks_data <- read_table('AdventData/Day3.txt', col_names = FALSE)
get_rucksack_weight <- function(rucksack_contents){
# Tokenise - Split the string into a vector of characters
tokens <- strsplit(rucksack_contents, "")[[1]]
# Split the vector in half into two vectors
first_half <- tokens[1:(length(tokens)/2)]
second_half <- tokens[(length(tokens)/2 + 1):length(tokens)]
# Find the intersect between the two halfs and find their score
which(c(letters, LETTERS) == intersect(first_half, second_half))[1]
}
# Call the function on every rucksack and sum the results
do.call(sum, lapply(rucksacks_data$X1, get_rucksack_weight))
As you finish identifying the misplaced items, the Elves come to you with another issue.
For safety, the Elves are divided into groups of three. Every Elf carries a badge that identifies their group. For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves. That is, if a group’s badge is item type B, then all three Elves will have item type B somewhere in their rucksack, and at most two of the Elves will be carrying any other item type.
The problem is that someone forgot to put this year’s updated authenticity sticker on the badges. All of the badges need to be pulled out of the rucksacks so the new authenticity stickers can be attached.
Additionally, nobody wrote down which item type corresponds to each group’s badges. The only way to tell which item type is the right one is by finding the one item type that is common between all three Elves in each group.
Every set of three lines in your list corresponds to a single group, but each group can have a different badge item type. So, in the above example, the first group’s rucksacks are the first three lines:
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
And the second group’s rucksacks are the next three lines:
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
In the first group, the only item type that appears in all three rucksacks is lowercase r; this must be their badges. In the second group, their badge item type must be Z.
Priorities for these items must still be found to organize the sticker attachment efforts: here, they are 18 (r) for the first group and 52 (Z) for the second group. The sum of these is 70.
Find the item type that corresponds to the badges of each three-Elf group. What is the sum of the priorities of those item types?
This part took a little longer - I didn’t know about pull
or reduce
which helped eliminate some of the hardcoded elements of my solution. This now should work find no matter how large the groups are - still assuming there only one mistake per group.
library(tidyverse)
# Compute the group Ids
rucksacks <- rucksacks_data %>%
mutate(group = ceiling(row_number()/3))
get_group_weight <- function(group_id){
# Find the common letter between the groups
priority_letter <- rucksacks[which(rucksacks$group == group_id),1] %>%
mutate(X1 = strsplit(X1, split = "")) %>% pull(X1) %>%
reduce(intersect)
# Score that letter
which(c(letters, LETTERS) == priority_letter)
}
# Call the function on all groups and sum the results
do.call(sum, lapply(1:100, get_group_weight))
Day 4
Problem 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).
For example, consider the following list of section assignment pairs:
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
For the first few pairs, this list means:
Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4), while the second Elf was assigned sections 6-8 (sections 6, 7, 8).
The Elves in the second pair were each assigned two sections.
The Elves in the third pair were each assigned three sections: one got sections 5, 6, and 7, while the other also got 7, plus 8 and 9.
This example list uses single-digit section IDs to make it easier to draw; your actual list might contain larger numbers. Visually, these pairs of section assignments look like this:
.234….. 2-4
…..678. 6-8
.23…… 2-3
…45…. 4-5
….567.. 5-7
……789 7-9
.2345678. 2-8
..34567.. 3-7
…..6… 6-6
…456… 4-6
.23456… 2-6
…45678. 4-8
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?
Problem 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.
In the above example, the first two pairs (2-4,6-8 and 2-3,4-5) don’t overlap, while the remaining four pairs (5-7,7-9, 2-8,3-7, 6-6,4-6, and 2-6,4-8) do overlap:
5-7,7-9 overlaps in a single section, 7.
2-8,3-7 overlaps all of the sections 3 through 7.
6-6,4-6 overlaps in a single section, 6.
2-6,4-8 overlaps in sections 4, 5, and 6.
So, in this example, the number of overlapping assignment pairs is 4.
In how many assignment pairs do the ranges overlap?
Today’s solution has ended up very similar to yesterdays. Maybe not quite as good as it’s a bit hard-codey. Although, today I’ve managed to solve both problems using one function, all you have to do is change one parameter and it’ll do all the work.
library(tidyverse)
# Read and clean the data
pairs <- read_table('AdventData/day4.txt', col_names = FALSE)
pairs <- pairs %>%
separate(X1, into = c("Elf_1", "Elf_2"), sep = ',') %>%
separate(Elf_1, into = c('Elf_1_Start', 'Elf_1_End')) %>%
separate(Elf_2, into = c('Elf_2_Start', 'Elf_2_End'))
# Solve the problem
identify_overlap <- function(row_number, complete_overlap = T){
row <- pairs[row_number,]
elf_1 <- as.character(seq(row$Elf_1_Start, row$Elf_1_End, by = 1))
elf_2 <- as.character(seq(row$Elf_2_Start, row$Elf_2_End, by = 1))
if(complete_overlap){
if(identical(intersect(elf_1, elf_2), elf_1) | identical(intersect(elf_1, elf_2), elf_2)) return(1)
else return(0)
} else{
if(length(intersect(elf_1, elf_2)) > 0) return(1)
else return(0)
}
}
# Change true to false to get the answer to part 2.
do.call(sum, lapply(1:nrow(pairs), function(x) identify_overlap(x, complete_overlap = T)))
Day 5
Problem 1
The expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged.
The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack.
The Elves don't want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark.
They do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input). For example:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
In this example, there are three stacks of crates. Stack 1 contains two crates: crate Z
is on the bottom, and crate N
is on top. Stack 2 contains three crates; from bottom to top, they are crates M
, C
, and D
. Finally, stack 3 contains a single crate, P
.
Then, the rearrangement procedure is given. In each step of the procedure, a quantity of crates is moved from one stack to a different stack. In the first step of the above rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this configuration:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
In the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a time, so the first crate to be moved (D
) ends up below the second and third crates:
[Z]
[N]
[C] [D]
[M] [P]
1 2 3
Then, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a time, crate C
ends up below crate M
:
[Z]
[N]
[M] [D]
[C] [P]
1 2 3
Finally, one crate is moved from stack 1 to stack 2:
[Z]
[N]
[D]
[C] [M] [P]
1 2 3
The Elves just need to know which crate will end up on top of each stack; in this example, the top crates are C
in stack 1, M
in stack 2, and Z
in stack 3, so you should combine these together and give the Elves the message CMZ
.
After the rearrangement procedure completes, what crate ends up on top of each stack?
Problem 2
As you watch the crane operator expertly rearrange the crates, you notice the process isn't following your prediction.
Some mud was covering the writing on the side of the crane, and you quickly wipe it away. The crane isn't a CrateMover 9000 - it's a CrateMover 9001.
The CrateMover 9001 is notable for many new and exciting features: air conditioning, leather seats, an extra cup holder, and the ability to pick up and move multiple crates at once.
Again considering the example above, the crates begin in the same configuration:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
Moving a single crate from stack 2 to stack 1 behaves the same as before:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
However, the action of moving three crates from stack 1 to stack 3 means that those three moved crates stay in the same order, resulting in this new configuration:
[D]
[N]
[C] [Z]
[M] [P]
1 2 3
Next, as both crates are moved from stack 2 to stack 1, they retain their order as well:
[D]
[N]
[C] [Z]
[M] [P]
1 2 3
Finally, a single crate is still moved from stack 1 to stack 2, but now it's crate C
that gets moved:
[D]
[N]
[Z]
[M] [C] [P]
1 2 3
In this example, the CrateMover 9001 has put the crates in a totally different order: MCD
.
Before the rearrangement process finishes, update your simulation so that the Elves know where they should stand to be ready to unload the final supplies. After the rearrangement procedure completes, what crate ends up on top of each stack?
Today got off to a bad start as I decided to slightly cheat and manually key in some of the input data. I decided to type in the initial configuration as a list of vectors, we can access and manipulate these fairly easily. Then the list of moves is just loaded in in the normal way and cleaned up.
The next step is to create a function which can take accept an order and carry it out on the configuration we have stored. move_crate
does this by first adding the selected crates to the new vector and then removes them from the old vector. The only thing that is a little bit spicy is the use of <<-
. This changes the global variable of crates
- it’s not just scoped to the function. This becomes important later when we lapply
as we need to access the results of the move_crate
function just after we’ve applied it to apply th next set of moves.
There is a flag in here for which crane we want to use, setting to T
or F
is what answers problem 1 or problem 2. Now we have a function that can carry out one set of rules, we just need to apply all the rules to our initial configuration - we can do this, like in previous weeks, using lapply
. This time, we don’t get right to the desired input after carrying out all the rules, we also need to get the top crate from each pile. We could, and probably should, go back and change move_crate
to give us this as the output - doing that would mean our lapply
does get us all the way to the answer. Instead, I’ve added it as a second step after the first lapply
and then wrapped all of that in a new function apply_crane_moves
. This is also where I decided to specify the inital configuration - although, this could be done anywhere really, as long as it is then passed to apply_crate_moves
as a variable.
library(tidyverse)
# I removed the initial configuration from the input and typed it in later
# This just loads the list of moves
data <- read_table("AdventData/day5.txt", col_names = FALSE) %>%
select(crates_to_move = X2,
from = X4,
to = X6)
# This function applies one move from the move list and saves the result over
# the global variable using <<-
move_crate <- function(crates_to_move, to, from, super_crane = F){
if(!super_crane) selected_crates <- rev(crates[[from]][1:crates_to_move])
else selected_crates <- crates[[from]][1:crates_to_move]
crates[[to]] <<- c(selected_crates, crates[[to]]) # Add the crates to the new pile
crates[[from]] <<- crates[[from]][-(1:crates_to_move)] # Remove the crates from the old pile
crates
}
apply_crane_moves <- function(move_list, super_crane){
# Our initial configuration
crates <<- list(
c("F", "H", "M", "T", "V", "L", "D"),
c("P", "N", "T", "C", "J", "G", "Q", "H"),
c("H", "P", "M", "D", "S", "R"),
c("F", "V", "B", "L"),
c("Q", "L", "G", "H", "N"),
c("P", "M", "R", "G", "D", "B", "W"),
c("Q", "L", "H", "C", "R", "N", "M", "G"),
c("W", "L", "C"),
c("T", "M", "Z", "J", "Q", "L", "D", "R")
)
#Apply move list
lapply(1:nrow(move_list), function(x) move_crate(data[x,]$crates_to_move, data[x,]$to, data[x,]$from, super_crane = super_crane))
# Get list of top crates
paste(unlist(lapply(crates, function(x) x[1])), collapse = '')
}
apply_crane_moves(data, F)
Day 6
Problem 1
The preparations are finally complete; you and the Elves leave camp on foot and begin to make your way toward the star fruit grove.
As you move through the dense undergrowth, one of the Elves gives you a handheld device. He says that it has many fancy features, but the most important one to set up right now is the communication system.
However, because he's heard you have significant experience dealing with signal-based systems, he convinced the other Elves that it would be okay to give you their one malfunctioning device - surely you'll have no problem fixing it.
As if inspired by comedic timing, the device emits a few colorful sparks.
To be able to communicate with the Elves, the device needs to lock on to their signal. The signal is a series of seemingly-random characters that the device receives one at a time.
To fix the communication system, you need to add a subroutine to the device that detects a start-of-packet marker in the datastream. In the protocol being used by the Elves, the start of a packet is indicated by a sequence of four characters that are all different.
The device will send your subroutine a datastream buffer (your puzzle input); your subroutine needs to identify the first position where the four most recently received characters were all different. Specifically, it needs to report the number of characters from the beginning of the buffer to the end of the first such four-character marker.
For example, suppose you receive the following datastream buffer:
mjqjpqmgbljsphdztnvjfqwrcgsmlb
After the first three characters (mjq
) have been received, there haven't been enough characters received yet to find the marker. The first time a marker could occur is after the fourth character is received, making the most recent four characters mjqj
. Because j
is repeated, this isn't a marker.
The first time a marker appears is after the seventh character arrives. Once it does, the last four characters received are jpqm
, which are all different. In this case, your subroutine should report the value 7
, because the first start-of-packet marker is complete after 7 characters have been processed.
Here are a few more examples:
bvwbjplbgvbhsrlpgdmjqwftvncz
: first marker after character5
nppdvjthqldpwncqszvftbrmjlhg
: first marker after character6
nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg
: first marker after character10
zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw
: first marker after character11
How many characters need to be processed before the first start-of-packet marker is detected?
Problem 2
Your device's communication system is correctly detecting packets, but still isn't working. It looks like it also needs to look for messages.
A start-of-message marker is just like a start-of-packet marker, except it consists of 14 distinct characters rather than 4.
Here are the first positions of start-of-message markers for all of the above examples:
mjqjpqmgbljsphdztnvjfqwrcgsmlb
: first marker after character19
bvwbjplbgvbhsrlpgdmjqwftvncz
: first marker after character23
nppdvjthqldpwncqszvftbrmjlhg
: first marker after character23
nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg
: first marker after character29
zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw
: first marker after character26
How many characters need to be processed before the first start-of-message marker is detected?
Slightly easier one today. I’ve over-engineered it a little bit and I feel like I’m heavily relying on base R as if I was back at university. I’ve answered both problems with one function again, we have a variable check_size
which can be used to solve an infinite number of these problems.
library(tidyverse)
## Load the data as a single string, the [[1]] might be unneeded
string <- read_lines("AventData/day6.txt")[[1]]
find_signal <- function(string, check_size){
check_uniqueness <- function(string_start, check_size){
# Get a section of the string
check_string <- str_split(string, "")[[1]][string_start:(string_start+(check_size-1))]
# Check for uniqueness and give other statistics
tibble(string = paste(check_string, collapse = ''),
is_unique = length(unique(check_string)) == length(check_string),
string_start,
string_end = string_start + (check_size-1))
}
# Call the function over the range - we could do the filtering now and just return the answer but I'd rather see the data we've created.
do.call(rbind, lapply(1:(nchar(string) - check_size), function(string_start) check_uniqueness(string_start, check_size)))
}
# Explore the output for the solution
output <- find_signal(string, 14)
output %>%
filter(is_unique == TRUE)
Avoiding functions and sticking a little bit more to TidyVerse.
library(tidyverse)
string <- read_lines("AdventData/day6.txt")[[1]]
check_length <- 3
tibble(start = 1:nchar(string), end = 1:nchar(string) + (check_length-1)) %>%
rowwise() %>%
mutate(string_segment = paste(str_split(string, "")[[1]][start:end], collapse = "")) %>%
mutate(unique = length(unique(str_split(string_segment, "")[[1]])) == length(str_split(string_segment, "")[[1]])) %>%
filter(unique) %>%
ungroup() %>%
slice(1) %>%
pull(end)
Day 7
You can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway?
The device the Elves gave you has problems with more than just its communication system. You try to run a system update:
$ system-update --please --pretty-please-with-sugar-on-top
Error: No space left on device
Perhaps you can delete some files to make space for the update?
You browse around the filesystem to assess the situation and save the resulting terminal output (your puzzle input). For example:
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
The filesystem consists of a tree of files (plain data) and directories (which can contain other directories or files). The outermost directory is called /
. You can navigate around the filesystem, moving into or out of directories and listing the contents of the directory you're currently in.
Within the terminal output, lines that begin with $
are commands you executed, very much like some modern computers:
cd
means change directory. This changes which directory is the current directory, but the specific result depends on the argument:cd x
moves in one level: it looks in the current directory for the directory namedx
and makes it the current directory.cd ..
moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory.cd /
switches the current directory to the outermost directory,/
.
ls
means list. It prints out all of the files and directories immediately contained by the current directory:123 abc
means that the current directory contains a file namedabc
with size123
.dir xyz
means that the current directory contains a directory namedxyz
.
Given the commands and output in the example above, you can determine that the filesystem looks visually like this:
- / (dir)
- a (dir)
- e (dir)
- i (file, size=584)
- f (file, size=29116)
- g (file, size=2557)
- h.lst (file, size=62596)
- b.txt (file, size=14848514)
- c.dat (file, size=8504156)
- d (dir)
- j (file, size=4060174)
- d.log (file, size=8033020)
- d.ext (file, size=5626152)
- k (file, size=7214296)
Here, there are four directories: /
(the outermost directory), a
and d
(which are in /
), and e
(which is in a
). These directories also contain files of various sizes.
Since the disk is full, your first step should probably be to find directories that are good candidates for deletion. To do this, you need to determine the total size of each directory. The total size of a directory is the sum of the sizes of the files it contains, directly or indirectly. (Directories themselves do not count as having any intrinsic size.)
The total sizes of the directories above can be found as follows:
- The total size of directory
e
is 584 because it contains a single filei
of size 584 and no other directories. - The directory
a
has total size 94853 because it contains filesf
(size 29116),g
(size 2557), andh.lst
(size 62596), plus filei
indirectly (a
containse
which containsi
). - Directory
d
has total size 24933642. - As the outermost directory,
/
contains every file. Its total size is 48381165, the sum of the size of every file.
To begin, find all of the directories with a total size of at most 100000, then calculate the sum of their total sizes. In the example above, these directories are a
and e
; the sum of their total sizes is 95437
(94853 + 584). (As in this example, this process can count files more than once!)
Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories?
I didn’t enjoy today. I think I’ve really over-engineered the solution. We have a big function which recursively goes through the command list and stores + updates what it has learnt about the file system so far. The output is possibly worth the work however, giving us a clean and tidy dataset to solve the questions. Problem 1 is solved with a simple summarise after the hard work has been done.
library(tidyverse)
data <- read_lines("AdventData/day7.txt")
data <- data[data != '$ ls'] %>% as.list
parse_directory <- function(command_list, current_directory = c('home'), current_list_position = 1, output = tibble(directory = character(), file_or_filesize = character(), filename = character(), directory_size = numeric())){
parsed_command <- str_split(command_list[[current_list_position]], " ")[[1]]
# Change directory if needed
if(parsed_command[1] == '$' & parsed_command[2] == 'cd'){
if (parsed_command[3] == '/') current_directory <- c('home')
else if (parsed_command[3] == '..') current_directory <- current_directory[-length(current_directory)]
else current_directory <- c(current_directory, parsed_command[3])
}
# Store file information if needed
if(!(parsed_command[1] == '$' & parsed_command[2] == 'cd')){
file_size <- parsed_command[1]
filename <- parsed_command[2]
directory_size <- 0
if(nrow(output %>% filter(directory == paste(current_directory, collapse = '/'))) != 0) {
directory_size <- output %>%
filter(directory == paste(current_directory, collapse = '/')) %>%
distinct(directory_size) %>%
pull(directory_size)
}
output <- output %>%
bind_rows(tibble(directory = paste(current_directory, collapse = '/'), file_or_filesize = file_size, filename = filename, directory_size = directory_size))
affected_directories <- lapply(1:length(current_directory), function(x) paste(current_directory[1:x], collapse = '/'))
output <- output %>%
mutate(directory_size = ifelse(directory %in% unlist(affected_directories),
ifelse(is.na(directory_size),0, directory_size) + ifelse(is.na(as.numeric(file_size)), 0, as.numeric(file_size)),
directory_size))
}
if(current_list_position < length(command_list)){
set_current_directory(command_list, current_directory, current_list_position + 1, output)
} else {
output
}
}
output <- parse_directory(data)
output %>%
distinct(directory, directory_size) %>%
filter(directory_size <= 100000)%>%
summarise(sum(directory_size))
Now, you're ready to choose a directory to delete.
The total disk space available to the filesystem is 70000000
. To run the update, you need unused space of at least 30000000
. You need to find a directory you can delete that will free up enough space to run the update.
In the example above, the total size of the outermost directory (and thus the total amount of used space) is 48381165
; this means that the size of the unused space must currently be 21618835
, which isn't quite the 30000000
required by the update. Therefore, the update still requires a directory with total size of at least 8381165
to be deleted before it can run.
To achieve this, you have the following options:
- Delete directory
e
, which would increase unused space by584
. - Delete directory
a
, which would increase unused space by94853
. - Delete directory
d
, which would increase unused space by24933642
. - Delete directory
/
, which would increase unused space by48381165
.
Directories e
and a
are both too small; deleting them would not free up enough space. However, directories d
and /
are both big enough! Between these, choose the smallest: d
, increasing unused space by 24933642
.
Find the smallest directory that, if deleted, would free up enough space on the filesystem to run the update. What is the total size of that directory?
Now we have our clean dataset, the follow up question is a fairly easy bit of filtering and arranging.
total <- output %>%
distinct(directory, directory_size) %>%
filter(directory == "home") %>%
pull(directory_size)
output %>%
distinct(directory, directory_size) %>%
filter(directory_size > (30000000 - (70000000 - total))) %>%
arrange(directory_size)
Day 8
The expedition comes across a peculiar patch of tall trees all planted carefully in a grid. The Elves explain that a previous expedition planted these trees as a reforestation effort. Now, they're curious if this would be a good location for a tree house.
First, determine whether there is enough tree cover here to keep a tree house hidden. To do this, you need to count the number of trees that are visible from outside the grid when looking directly along a row or column.
The Elves have already launched a quadcopter to generate a map with the height of each tree (your puzzle input). For example:
30373
25512
65332
33549
35390
Each tree is represented as a single digit whose value is its height, where 0
is the shortest and 9
is the tallest.
A tree is visible if all of the other trees between it and an edge of the grid are shorter than it. Only consider trees in the same row or column; that is, only look up, down, left, or right from any given tree.
All of the trees around the edge of the grid are visible - since they are already on the edge, there are no trees to block the view. In this example, that only leaves the interior nine trees to consider:
- The top-left
5
is visible from the left and top. (It isn't visible from the right or bottom since other trees of height5
are in the way.) - The top-middle
5
is visible from the top and right. - The top-right
1
is not visible from any direction; for it to be visible, there would need to only be trees of height 0 between it and an edge. - The left-middle
5
is visible, but only from the right. - The center
3
is not visible from any direction; for it to be visible, there would need to be only trees of at most height2
between it and an edge. - The right-middle
3
is visible from the right. - In the bottom row, the middle
5
is visible, but the3
and4
are not.
With 16 trees visible on the edge and another 5 visible in the interior, a total of 21
trees are visible in this arrangement.
Consider your map; how many trees are visible from outside the grid?
Far from the best solution today. This felt a lot like being back in university and writing mathematicians code - it’s not particularly readable or nice but it makes use of matrices.
library(tidyverse)
data <- read_lines("AdventData/day8.txt")
data <- do.call(rbind, lapply(strsplit(data, ""), as.numeric))
map_visibility <- function(matrix_position, matrix){
y <- matrix_position[1]
x <- matrix_position[2]
n <- dim(matrix)[1]
m <- dim(matrix)[2]
if(x == 1 | y == 1 | y == dim(matrix)[2] | x == dim(matrix)[1]){
# On the edge
return(TRUE)
} else if (matrix[x,y] > max(matrix[x, 1:(y-1)]) | matrix[x,y] > max(matrix[x, (y+1):n])) {
# Visible from y direction
return(TRUE)
} else if (matrix[x,y] > max(matrix[1:(x-1), y]) | matrix[x,y] > max(matrix[(x+1):m, y])) {
# Visible from x direction
return(TRUE)
} else {
return(FALSE)
}
}
sum(apply(expand.grid(x = 1:dim(data)[1], y = 1:dim(data)[2]), MARGIN = 1, function(position) map_visibility(position, data)))
Content with the amount of tree cover available, the Elves just need to know the best spot to build their tree house: they would like to be able to see a lot of trees.
To measure the viewing distance from a given tree, look up, down, left, and right from that tree; stop if you reach an edge or at the first tree that is the same height or taller than the tree under consideration. (If a tree is right on the edge, at least one of its viewing distances will be zero.)
The Elves don't care about distant trees taller than those found by the rules above; the proposed tree house has large eaves to keep it dry, so they wouldn't be able to see higher than the tree house anyway.
In the example above, consider the middle 5
in the second row:
30373
25512
65332
33549
35390
- Looking up, its view is not blocked; it can see
1
tree (of height3
). - Looking left, its view is blocked immediately; it can see only
1
tree (of height5
, right next to it). - Looking right, its view is not blocked; it can see
2
trees. - Looking down, its view is blocked eventually; it can see
2
trees (one of height3
, then the tree of height5
that blocks its view).
A tree's scenic score is found by multiplying together its viewing distance in each of the four directions. For this tree, this is 4
(found by multiplying 1 * 1 * 2 * 2
).
However, you can do even better: consider the tree of height 5
in the middle of the fourth row:
30373
25512
65332
33549
35390
- Looking up, its view is blocked at
2
trees (by another tree with a height of5
). - Looking left, its view is not blocked; it can see
2
trees. - Looking down, its view is also not blocked; it can see
1
tree. - Looking right, its view is blocked at
2
trees (by a massive tree of height9
).
This tree's scenic score is 8
(2 * 2 * 1 * 2
); this is the ideal spot for the tree house.
Consider each tree on your map. What is the highest scenic score possible for any tree?
Very much the same again just with a new heavily maths-y function. This would be a good one to come back to with some plots but now is not the time for that!
map_distance <- function(matrix_position, matrix){
y_t = matrix_position[1]
x_t = matrix_position[2]
n_t <- dim(data)[1]
m_t <- dim(data)[2]
if(x_t == 1 | y_t == 1 | y_t == dim(matrix)[2] | x_t == dim(matrix)[1]) return(0)
calculate_distance <- function(sequence){
if(sum(sequence) == 0) {
length(sequence)
} else{
min(which(sequence))
}
}
down <- rev(data[x_t, 1:(y_t-1)]) >= data[x_t,y_t]
up <- data[x_t, (y_t+1):n_t] >= data[x_t,y_t]
left <- rev(data[1:(x_t-1), y_t]) >= data[x_t,y_t]
right <- data[(x_t+1):m_t, y_t] >= data[x_t,y_t]
calculate_distance(left) * calculate_distance(right) * calculate_distance(up) * calculate_distance(down)
}
max(apply(expand.grid(x = 1:dim(data)[1], y = 1:dim(data)[2]), MARGIN = 1, function(position) map_distance(position, data)))
Day 9
This rope bridge creaks as you walk along it. You aren't sure how old it is, or whether it can even support your weight.
It seems to support the Elves just fine, though. The bridge spans a gorge which was carved out by the massive river far below you.
You step carefully; as you do, the ropes stretch and twist. You decide to distract yourself by modeling rope physics; maybe you can even figure out where not to step.
Consider a rope with a knot at each end; these knots mark the head and the tail of the rope. If the head moves far enough away from the tail, the tail is pulled toward the head.
Due to nebulous reasoning involving Planck lengths, you should be able to model the positions of the knots on a two-dimensional grid. Then, by following a hypothetical series of motions (your puzzle input) for the head, you can determine how the tail will move.
Due to the aforementioned Planck lengths, the rope must be quite short; in fact, the head (H
) and tail (T
) must always be touching (diagonally adjacent and even overlapping both count as touching):
....
.TH.
....
….
.H..
..T.
….
…
.H. (H covers T)
…
If the head is ever two steps directly up, down, left, or right from the tail, the tail must also move one step in that direction so it remains close enough:
..... ..... .....
.TH.. -> .T.H. -> ..TH.
..... ..... .....
… … …
.T. .T. …
.H. -> … -> .T.
… .H. .H.
… … …
Otherwise, if the head and tail aren't touching and aren't in the same row or column, the tail always moves one step diagonally to keep up:
..... ..... .....
..... ..H.. ..H..
..H.. -> ..... -> ..T..
.T... .T... .....
..... ..... .....
….. ….. …..
….. ….. …..
..H.. -> …H. -> ..TH.
.T… .T… …..
….. ….. …..
You just need to work out where the tail goes as the head follows a series of motions. Assume the head and the tail both start at the same position, overlapping.
For example:
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
This series of motions moves the head right four steps, then up four steps, then left three steps, then down one step, and so on. After each step, you'll need to update the position of the tail if the step means the head is no longer adjacent to the tail. Visually, these motions occur as follows (s
marks the starting position as a reference point):
== Initial State ==
……
……
……
……
H….. (H covers T, s)
== R 4 ==
……
……
……
……
TH…. (T covers s)
……
……
……
……
sTH…
……
……
……
……
s.TH..
……
……
……
……
s..TH.
== U 4 ==
……
……
……
….H.
s..T..
……
……
….H.
….T.
s…..
……
….H.
….T.
……
s…..
….H.
….T.
……
……
s…..
== L 3 ==
…H..
….T.
……
……
s…..
..HT..
……
……
……
s…..
.HT…
……
……
……
s…..
== D 1 ==
..T…
.H….
……
……
s…..
== R 4 ==
..T…
..H…
……
……
s…..
..T…
…H..
……
……
s…..
……
…TH.
……
……
s…..
……
….TH
……
……
s…..
== D 1 ==
……
….T.
…..H
……
s…..
== L 5 ==
……
….T.
….H.
……
s…..
……
….T.
…H..
……
s…..
……
……
..HT..
……
s…..
……
……
.HT…
……
s…..
……
……
HT….
……
s…..
== R 2 ==
……
……
.H…. (H covers T)
……
s…..
……
……
.TH…
……
s…..
After simulating the rope, you can count up all of the positions the tail visited at least once. In this diagram, s
again marks the starting position (which the tail also visited) and #
marks other positions the tail visited:
..##..
...##.
.####.
....#.
s###..
So, there are 13
positions the tail visited at least once.
Simulate your complete hypothetical series of motions. How many positions does the tail of the rope visit at least once?
A rope snaps! Suddenly, the river is getting a lot closer than you remember. The bridge is still there, but some of the ropes that broke are now whipping toward you as you fall through the air!
The ropes are moving too quickly to grab; you only have a few seconds to choose how to arch your body to avoid being hit. Fortunately, your simulation can be extended to support longer ropes.
Rather than two knots, you now must simulate a rope consisting of ten knots. One knot is still the head of the rope and moves according to the series of motions. Each knot further down the rope follows the knot in front of it using the same rules as before.
Using the same series of motions as the above example, but with the knots marked H
, 1
, 2
, ..., 9
, the motions now occur as follows:
== Initial State ==
……
……
……
……
H….. (H covers 1, 2, 3, 4, 5, 6, 7, 8, 9, s)
== R 4 ==
……
……
……
……
1H…. (1 covers 2, 3, 4, 5, 6, 7, 8, 9, s)
……
……
……
……
21H… (2 covers 3, 4, 5, 6, 7, 8, 9, s)
……
……
……
……
321H.. (3 covers 4, 5, 6, 7, 8, 9, s)
……
……
……
……
4321H. (4 covers 5, 6, 7, 8, 9, s)
== U 4 ==
……
……
……
….H.
4321.. (4 covers 5, 6, 7, 8, 9, s)
……
……
….H.
.4321.
5….. (5 covers 6, 7, 8, 9, s)
……
….H.
….1.
.432..
5….. (5 covers 6, 7, 8, 9, s)
….H.
….1.
..432.
.5….
6….. (6 covers 7, 8, 9, s)
== L 3 ==
…H..
….1.
..432.
.5….
6….. (6 covers 7, 8, 9, s)
..H1..
…2..
..43..
.5….
6….. (6 covers 7, 8, 9, s)
.H1…
…2..
..43..
.5….
6….. (6 covers 7, 8, 9, s)
== D 1 ==
..1…
.H.2..
..43..
.5….
6….. (6 covers 7, 8, 9, s)
== R 4 ==
..1…
..H2..
..43..
.5….
6….. (6 covers 7, 8, 9, s)
..1…
…H.. (H covers 2)
..43..
.5….
6….. (6 covers 7, 8, 9, s)
……
…1H. (1 covers 2)
..43..
.5….
6….. (6 covers 7, 8, 9, s)
……
…21H
..43..
.5….
6….. (6 covers 7, 8, 9, s)
== D 1 ==
……
…21.
..43.H
.5….
6….. (6 covers 7, 8, 9, s)
== L 5 ==
……
…21.
..43H.
.5….
6….. (6 covers 7, 8, 9, s)
……
…21.
..4H.. (H covers 3)
.5….
6….. (6 covers 7, 8, 9, s)
……
…2..
..H1.. (H covers 4; 1 covers 3)
.5….
6….. (6 covers 7, 8, 9, s)
……
…2..
.H13.. (1 covers 4)
.5….
6….. (6 covers 7, 8, 9, s)
……
……
H123.. (2 covers 4)
.5….
6….. (6 covers 7, 8, 9, s)
== R 2 ==
……
……
.H23.. (H covers 1; 2 covers 4)
.5….
6….. (6 covers 7, 8, 9, s)
……
……
.1H3.. (H covers 2, 4)
.5….
6….. (6 covers 7, 8, 9, s)
Now, you need to keep track of the positions the new tail, 9
, visits. In this example, the tail never moves, and so it only visits 1
position. However, be careful: more types of motion are possible than before, so you might want to visually compare your simulated rope to the one above.
Here's a larger example:
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
These motions occur as follows (individual steps are not shown):
== Initial State ==
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
………..H………….. (H covers 1, 2, 3, 4, 5, 6, 7, 8, 9, s)
……………………..
……………………..
……………………..
……………………..
……………………..
== R 5 ==
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
………..54321H……… (5 covers 6, 7, 8, 9, s)
……………………..
……………………..
……………………..
……………………..
……………………..
== U 8 ==
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
…………….H………
…………….1………
…………….2………
…………….3………
……………54………
…………..6………..
………….7…………
…………8………….
………..9………….. (9 covers s)
……………………..
……………………..
……………………..
……………………..
……………………..
== L 8 ==
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……..H1234………….
…………5………….
…………6………….
…………7………….
…………8………….
…………9………….
……………………..
……………………..
………..s…………..
……………………..
……………………..
……………………..
……………………..
……………………..
== D 3 ==
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
………2345………….
……..1…6………….
……..H…7………….
…………8………….
…………9………….
……………………..
……………………..
………..s…………..
……………………..
……………………..
……………………..
……………………..
……………………..
== R 17 ==
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
…………….987654321H
……………………..
……………………..
……………………..
……………………..
………..s…………..
……………………..
……………………..
……………………..
……………………..
……………………..
== D 10 ==
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
………..s………98765
…………………….4
…………………….3
…………………….2
…………………….1
…………………….H
== L 25 ==
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
………..s…………..
……………………..
……………………..
……………………..
……………………..
H123456789…………….
== U 20 ==
H…………………….
1…………………….
2…………………….
3…………………….
4…………………….
5…………………….
6…………………….
7…………………….
8…………………….
9…………………….
……………………..
……………………..
……………………..
……………………..
……………………..
………..s…………..
……………………..
……………………..
……………………..
……………………..
……………………..
Now, the tail (9
) visits 36
positions (including s
) at least once:
..........................
..........................
..........................
..........................
..........................
..........................
..........................
..........................
..........................
#.........................
#.............###.........
#............#...#........
.#..........#.....#.......
..#..........#.....#......
...#........#.......#.....
....#......s.........#....
.....#..............#.....
......#............#......
.......#..........#.......
........#........#........
.........########.........
Simulate your complete series of motions on a larger rope with ten knots. How many positions does the tail of the rope visit at least once?
Another very mathematical solution which felt like it came straight from university. Broke my own rule about not using for loops today but it meant I had to use my brain a little bit less. Defining a massive 1000 by 1000 matrix feels a little bit wooly but otherwise I think we’re quite efficient.
move_list <- read_table("AdventData/day9.txt", col_names = F)
apply_move <- function(direction, move_distance){
# Define move list
moves <- list(U = c(-1, 0), D = c(1, 0), L = c(0, -1), R = c(0, 1))
# Apply the defined move for the defined amount of times
for(i in 1:move_distance){
# Move the head
positions[[1]] <<- positions[[1]] + moves[direction][[1]]
# Move the rest of the rope based on the previous knot
for(j in 2:length(positions)){
if(any(abs(positions[[j-1]] - positions[[j]]) > 1)) {
positions[[j]] <<- positions[[j]] + sign(positions[[j-1]] - positions[[j]])
}
}
# Mark where the tail has been
area[positions[[j]][1], positions[[j]][2]] <<- 1
}
}
calculate_distance <- function(rope_size){
# Define a big area to work in
area <<- matrix(0,nrow = 1000, ncol = 1000)
positions <<- replicate(rope_size, c(500,500), simplify = FALSE)
apply(move_list, 1, function(x) apply_move(x[1], x[2]))
sum(area)
}
calculate_distance(2)
calculate_distance(10)
Day 10
You avoid the ropes, plunge into the river, and swim to shore.
The Elves yell something about meeting back up with them upriver, but the river is too loud to tell exactly what they're saying. They finish crossing the bridge and disappear from view.
Situations like this must be why the Elves prioritized getting the communication system on your handheld device working. You pull it out of your pack, but the amount of water slowly draining from a big crack in its screen tells you it probably won't be of much immediate use.
Unless, that is, you can design a replacement for the device's video system! It seems to be some kind of cathode-ray tube screen and simple CPU that are both driven by a precise clock circuit. The clock circuit ticks at a constant rate; each tick is called a cycle.
Start by figuring out the signal being sent by the CPU. The CPU has a single register, X
, which starts with the value 1
. It supports only two instructions:
addx V
takes two cycles to complete. After two cycles, theX
register is increased by the valueV
. (V
can be negative.)noop
takes one cycle to complete. It has no other effect.
The CPU uses these instructions in a program (your puzzle input) to, somehow, tell the screen what to draw.
Consider the following small program:
noop
addx 3
addx -5
Execution of this program proceeds as follows:
- At the start of the first cycle, the
noop
instruction begins execution. During the first cycle,X
is1
. After the first cycle, thenoop
instruction finishes execution, doing nothing. - At the start of the second cycle, the
addx 3
instruction begins execution. During the second cycle,X
is still1
. - During the third cycle,
X
is still1
. After the third cycle, theaddx 3
instruction finishes execution, settingX
to4
. - At the start of the fourth cycle, the
addx -5
instruction begins execution. During the fourth cycle,X
is still4
. - During the fifth cycle,
X
is still4
. After the fifth cycle, theaddx -5
instruction finishes execution, settingX
to-1
.
Maybe you can learn something by looking at the value of the X
register throughout execution. For now, consider the signal strength (the cycle number multiplied by the value of the X
register) during the 20th cycle and every 40 cycles after that (that is, during the 20th, 60th, 100th, 140th, 180th, and 220th cycles).
For example, consider this larger program:
addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop
The interesting signal strengths can be determined as follows:
- During the 20th cycle, register
X
has the value21
, so the signal strength is 20 * 21 = 420. (The 20th cycle occurs in the middle of the secondaddx -1
, so the value of registerX
is the starting value,1
, plus all of the otheraddx
values up to that point: 1 + 15 - 11 + 6 - 3 + 5 - 1 - 8 + 13 + 4 = 21.) - During the 60th cycle, register
X
has the value19
, so the signal strength is 60 * 19 =1140
. - During the 100th cycle, register
X
has the value18
, so the signal strength is 100 * 18 =1800
. - During the 140th cycle, register
X
has the value21
, so the signal strength is 140 * 21 =2940
. - During the 180th cycle, register
X
has the value16
, so the signal strength is 180 * 16 =2880
. - During the 220th cycle, register
X
has the value18
, so the signal strength is 220 * 18 =3960
.
The sum of these signal strengths is 13140
.
Find the signal strength during the 20th, 60th, 100th, 140th, 180th, and 220th cycles. What is the sum of these six signal strengths?
It seems like the X
register controls the horizontal position of a sprite. Specifically, the sprite is 3 pixels wide, and the X
register sets the horizontal position of the middle of that sprite. (In this system, there is no such thing as "vertical position": if the sprite's horizontal position puts its pixels where the CRT is currently drawing, then those pixels will be drawn.)
You count the pixels on the CRT: 40 wide and 6 high. This CRT screen draws the top row of pixels left-to-right, then the row below that, and so on. The left-most pixel in each row is in position 0
, and the right-most pixel in each row is in position 39
.
Like the CPU, the CRT is tied closely to the clock circuit: the CRT draws a single pixel during each cycle. Representing each pixel of the screen as a #
, here are the cycles during which the first and last pixel in each row are drawn:
Cycle 1 -> ######################################## <- Cycle 40
Cycle 41 -> ######################################## <- Cycle 80
Cycle 81 -> ######################################## <- Cycle 120
Cycle 121 -> ######################################## <- Cycle 160
Cycle 161 -> ######################################## <- Cycle 200
Cycle 201 -> ######################################## <- Cycle 240
So, by carefully timing the CPU instructions and the CRT drawing operations, you should be able to determine whether the sprite is visible the instant each pixel is drawn. If the sprite is positioned such that one of its three pixels is the pixel currently being drawn, the screen produces a lit pixel (#
); otherwise, the screen leaves the pixel dark (.
).
The first few pixels from the larger example above are drawn as follows:
Sprite position: ###.....................................
Start cycle 1: begin executing addx 15
During cycle 1: CRT draws pixel in position 0
Current CRT row: #
During cycle 2: CRT draws pixel in position 1
Current CRT row: ##
End of cycle 2: finish executing addx 15 (Register X is now 16)
Sprite position: ……………###………………….
Start cycle 3: begin executing addx -11
During cycle 3: CRT draws pixel in position 2
Current CRT row: ##.
During cycle 4: CRT draws pixel in position 3
Current CRT row: ##..
End of cycle 4: finish executing addx -11 (Register X is now 5)
Sprite position: ….###……………………………
Start cycle 5: begin executing addx 6
During cycle 5: CRT draws pixel in position 4
Current CRT row: ##..#
During cycle 6: CRT draws pixel in position 5
Current CRT row: ##..##
End of cycle 6: finish executing addx 6 (Register X is now 11)
Sprite position: ……….###………………………
Start cycle 7: begin executing addx -3
During cycle 7: CRT draws pixel in position 6
Current CRT row: ##..##.
During cycle 8: CRT draws pixel in position 7
Current CRT row: ##..##..
End of cycle 8: finish executing addx -3 (Register X is now 8)
Sprite position: …….###…………………………
Start cycle 9: begin executing addx 5
During cycle 9: CRT draws pixel in position 8
Current CRT row: ##..##..#
During cycle 10: CRT draws pixel in position 9
Current CRT row: ##..##..##
End of cycle 10: finish executing addx 5 (Register X is now 13)
Sprite position: …………###…………………….
Start cycle 11: begin executing addx -1
During cycle 11: CRT draws pixel in position 10
Current CRT row: ##..##..##.
During cycle 12: CRT draws pixel in position 11
Current CRT row: ##..##..##..
End of cycle 12: finish executing addx -1 (Register X is now 12)
Sprite position: ………..###……………………..
Start cycle 13: begin executing addx -8
During cycle 13: CRT draws pixel in position 12
Current CRT row: ##..##..##..#
During cycle 14: CRT draws pixel in position 13
Current CRT row: ##..##..##..##
End of cycle 14: finish executing addx -8 (Register X is now 4)
Sprite position: …###…………………………….
Start cycle 15: begin executing addx 13
During cycle 15: CRT draws pixel in position 14
Current CRT row: ##..##..##..##.
During cycle 16: CRT draws pixel in position 15
Current CRT row: ##..##..##..##..
End of cycle 16: finish executing addx 13 (Register X is now 17)
Sprite position: …………….###…………………
Start cycle 17: begin executing addx 4
During cycle 17: CRT draws pixel in position 16
Current CRT row: ##..##..##..##..#
During cycle 18: CRT draws pixel in position 17
Current CRT row: ##..##..##..##..##
End of cycle 18: finish executing addx 4 (Register X is now 21)
Sprite position: ………………..###……………..
Start cycle 19: begin executing noop
During cycle 19: CRT draws pixel in position 18
Current CRT row: ##..##..##..##..##.
End of cycle 19: finish executing noop
Start cycle 20: begin executing addx -1
During cycle 20: CRT draws pixel in position 19
Current CRT row: ##..##..##..##..##..
During cycle 21: CRT draws pixel in position 20
Current CRT row: ##..##..##..##..##..#
End of cycle 21: finish executing addx -1 (Register X is now 20)
Sprite position: ……………….###………………
Allowing the program to run to completion causes the CRT to produce the following image:
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
Render the image given by your program. What eight capital letters appear on your CRT?
Today’s solution is much more TidyVerse-y than the last few days - it could be a lot better and possibly sticking to the tibble structure might have made everything conceptually a lot more difficult.
library(tidyverse)
data <- read_table("AdventData/day10.txt", col_names = F) %>%
mutate(Command = X1, Value = ifelse(is.na(X2), 0, X2),
Cycle = ifelse(Command == 'addx', 2, 1),
Value = cumsum(Value) + 1, Cycle = cumsum(Cycle)) %>%
select(Cycle, Value)
data <- tibble(Cycle = 1:240) %>%
left_join(data) %>%
mutate(x = replace_na(coalesce(Value, lag(Value)), 1),
Signal_Strength = replace_na(Cycle * coalesce(Value, lag(Value)), 0))
# Answer 1
data %>%
filter(Cycle %in% (c(20, 60, 100, 140, 180, 220))) %>%
summarise(sum(Signal_Strength))
# Answer 2
data %>%
mutate(start_x = replace_na(lag(x),1)) %>%
rowwise() %>%
mutate(row = ceiling(Cycle / 40),
column = (Cycle-1) %% 40,
pixel_light = ifelse(between(column, start_x - 1, start_x + 1), '#','.')) %>%
ungroup() %>%
select(column, row, pixel_light) %>%
spread(column, pixel_light) %>%
select(-row) %>%
as.matrix()
Day 11
As you finally start making your way upriver, you realize your pack is much lighter than you remember. Just then, one of the items from your pack goes flying overhead. Monkeys are playing Keep Away with your missing things!
To get your stuff back, you need to be able to predict where the monkeys will throw your items. After some careful observation, you realize the monkeys operate based on how worried you are about each item.
You take some notes (your puzzle input) on the items each monkey currently has, how worried you are about those items, and how the monkey makes decisions based on your worry level. For example:
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
Each monkey has several attributes:
Starting items
lists your worry level for each item the monkey is currently holding in the order they will be inspected.Operation
shows how your worry level changes as that monkey inspects an item. (An operation likenew = old * 5
means that your worry level after the monkey inspected the item is five times whatever your worry level was before inspection.)Test
shows how the monkey uses your worry level to decide where to throw an item next.If true
shows what happens with an item if theTest
was true.If false
shows what happens with an item if theTest
was false.
After each monkey inspects an item but before it tests your worry level, your relief that the monkey's inspection didn't damage the item causes your worry level to be divided by three and rounded down to the nearest integer.
The monkeys take turns inspecting and throwing items. On a single monkey's turn, it inspects and throws all of the items it is holding one at a time and in the order listed. Monkey 0
goes first, then monkey 1
, and so on until each monkey has had one turn. The process of each monkey taking a single turn is called a round.
When a monkey throws an item to another monkey, the item goes on the end of the recipient monkey's list. A monkey that starts a round with no items could end up inspecting and throwing many items by the time its turn comes around. If a monkey is holding no items at the start of its turn, its turn ends.
In the above example, the first round proceeds as follows:
Monkey 0:
Monkey inspects an item with a worry level of 79.
Worry level is multiplied by 19 to 1501.
Monkey gets bored with item. Worry level is divided by 3 to 500.
Current worry level is not divisible by 23.
Item with worry level 500 is thrown to monkey 3.
Monkey inspects an item with a worry level of 98.
Worry level is multiplied by 19 to 1862.
Monkey gets bored with item. Worry level is divided by 3 to 620.
Current worry level is not divisible by 23.
Item with worry level 620 is thrown to monkey 3.
Monkey 1:
Monkey inspects an item with a worry level of 54.
Worry level increases by 6 to 60.
Monkey gets bored with item. Worry level is divided by 3 to 20.
Current worry level is not divisible by 19.
Item with worry level 20 is thrown to monkey 0.
Monkey inspects an item with a worry level of 65.
Worry level increases by 6 to 71.
Monkey gets bored with item. Worry level is divided by 3 to 23.
Current worry level is not divisible by 19.
Item with worry level 23 is thrown to monkey 0.
Monkey inspects an item with a worry level of 75.
Worry level increases by 6 to 81.
Monkey gets bored with item. Worry level is divided by 3 to 27.
Current worry level is not divisible by 19.
Item with worry level 27 is thrown to monkey 0.
Monkey inspects an item with a worry level of 74.
Worry level increases by 6 to 80.
Monkey gets bored with item. Worry level is divided by 3 to 26.
Current worry level is not divisible by 19.
Item with worry level 26 is thrown to monkey 0.
Monkey 2:
Monkey inspects an item with a worry level of 79.
Worry level is multiplied by itself to 6241.
Monkey gets bored with item. Worry level is divided by 3 to 2080.
Current worry level is divisible by 13.
Item with worry level 2080 is thrown to monkey 1.
Monkey inspects an item with a worry level of 60.
Worry level is multiplied by itself to 3600.
Monkey gets bored with item. Worry level is divided by 3 to 1200.
Current worry level is not divisible by 13.
Item with worry level 1200 is thrown to monkey 3.
Monkey inspects an item with a worry level of 97.
Worry level is multiplied by itself to 9409.
Monkey gets bored with item. Worry level is divided by 3 to 3136.
Current worry level is not divisible by 13.
Item with worry level 3136 is thrown to monkey 3.
Monkey 3:
Monkey inspects an item with a worry level of 74.
Worry level increases by 3 to 77.
Monkey gets bored with item. Worry level is divided by 3 to 25.
Current worry level is not divisible by 17.
Item with worry level 25 is thrown to monkey 1.
Monkey inspects an item with a worry level of 500.
Worry level increases by 3 to 503.
Monkey gets bored with item. Worry level is divided by 3 to 167.
Current worry level is not divisible by 17.
Item with worry level 167 is thrown to monkey 1.
Monkey inspects an item with a worry level of 620.
Worry level increases by 3 to 623.
Monkey gets bored with item. Worry level is divided by 3 to 207.
Current worry level is not divisible by 17.
Item with worry level 207 is thrown to monkey 1.
Monkey inspects an item with a worry level of 1200.
Worry level increases by 3 to 1203.
Monkey gets bored with item. Worry level is divided by 3 to 401.
Current worry level is not divisible by 17.
Item with worry level 401 is thrown to monkey 1.
Monkey inspects an item with a worry level of 3136.
Worry level increases by 3 to 3139.
Monkey gets bored with item. Worry level is divided by 3 to 1046.
Current worry level is not divisible by 17.
Item with worry level 1046 is thrown to monkey 1.
After round 1, the monkeys are holding items with these worry levels:
Monkey 0: 20, 23, 27, 26
Monkey 1: 2080, 25, 167, 207, 401, 1046
Monkey 2:
Monkey 3:
Monkeys 2 and 3 aren't holding any items at the end of the round; they both inspected items during the round and threw them all before the round ended.
This process continues for a few more rounds:
After round 2, the monkeys are holding items with these worry levels:
Monkey 0: 695, 10, 71, 135, 350
Monkey 1: 43, 49, 58, 55, 362
Monkey 2:
Monkey 3:
After round 3, the monkeys are holding items with these worry levels:
Monkey 0: 16, 18, 21, 20, 122
Monkey 1: 1468, 22, 150, 286, 739
Monkey 2:
Monkey 3:
After round 4, the monkeys are holding items with these worry levels:
Monkey 0: 491, 9, 52, 97, 248, 34
Monkey 1: 39, 45, 43, 258
Monkey 2:
Monkey 3:
After round 5, the monkeys are holding items with these worry levels:
Monkey 0: 15, 17, 16, 88, 1037
Monkey 1: 20, 110, 205, 524, 72
Monkey 2:
Monkey 3:
After round 6, the monkeys are holding items with these worry levels:
Monkey 0: 8, 70, 176, 26, 34
Monkey 1: 481, 32, 36, 186, 2190
Monkey 2:
Monkey 3:
After round 7, the monkeys are holding items with these worry levels:
Monkey 0: 162, 12, 14, 64, 732, 17
Monkey 1: 148, 372, 55, 72
Monkey 2:
Monkey 3:
After round 8, the monkeys are holding items with these worry levels:
Monkey 0: 51, 126, 20, 26, 136
Monkey 1: 343, 26, 30, 1546, 36
Monkey 2:
Monkey 3:
After round 9, the monkeys are holding items with these worry levels:
Monkey 0: 116, 10, 12, 517, 14
Monkey 1: 108, 267, 43, 55, 288
Monkey 2:
Monkey 3:
After round 10, the monkeys are holding items with these worry levels:
Monkey 0: 91, 16, 20, 98
Monkey 1: 481, 245, 22, 26, 1092, 30
Monkey 2:
Monkey 3:
…
After round 15, the monkeys are holding items with these worry levels:
Monkey 0: 83, 44, 8, 184, 9, 20, 26, 102
Monkey 1: 110, 36
Monkey 2:
Monkey 3:
…
After round 20, the monkeys are holding items with these worry levels:
Monkey 0: 10, 12, 14, 26, 34
Monkey 1: 245, 93, 53, 199, 115
Monkey 2:
Monkey 3:
Chasing all of the monkeys at once is impossible; you're going to have to focus on the two most active monkeys if you want any hope of getting your stuff back. Count the total number of times each monkey inspects items over 20 rounds:
Monkey 0 inspected items 101 times.
Monkey 1 inspected items 95 times.
Monkey 2 inspected items 7 times.
Monkey 3 inspected items 105 times.
In this example, the two most active monkeys inspected items 101 and 105 times. The level of monkey business in this situation can be found by multiplying these together: 10605
.
Figure out which monkeys to chase by counting how many items they inspect over 20 rounds. What is the level of monkey business after 20 rounds of stuff-slinging simian shenanigans?
You're worried you might not ever get your items back. So worried, in fact, that your relief that a monkey's inspection didn't damage an item no longer causes your worry level to be divided by three.
Unfortunately, that relief was all that was keeping your worry levels from reaching ridiculous levels. You'll need to find another way to keep your worry levels manageable.
At this rate, you might be putting up with these monkeys for a very long time - possibly 10000
rounds!
With these new rules, you can still figure out the monkey business after 10000 rounds. Using the same example above:
== After round 1 ==
Monkey 0 inspected items 2 times.
Monkey 1 inspected items 4 times.
Monkey 2 inspected items 3 times.
Monkey 3 inspected items 6 times.
== After round 20 ==
Monkey 0 inspected items 99 times.
Monkey 1 inspected items 97 times.
Monkey 2 inspected items 8 times.
Monkey 3 inspected items 103 times.
== After round 1000 ==
Monkey 0 inspected items 5204 times.
Monkey 1 inspected items 4792 times.
Monkey 2 inspected items 199 times.
Monkey 3 inspected items 5192 times.
== After round 2000 ==
Monkey 0 inspected items 10419 times.
Monkey 1 inspected items 9577 times.
Monkey 2 inspected items 392 times.
Monkey 3 inspected items 10391 times.
== After round 3000 ==
Monkey 0 inspected items 15638 times.
Monkey 1 inspected items 14358 times.
Monkey 2 inspected items 587 times.
Monkey 3 inspected items 15593 times.
== After round 4000 ==
Monkey 0 inspected items 20858 times.
Monkey 1 inspected items 19138 times.
Monkey 2 inspected items 780 times.
Monkey 3 inspected items 20797 times.
== After round 5000 ==
Monkey 0 inspected items 26075 times.
Monkey 1 inspected items 23921 times.
Monkey 2 inspected items 974 times.
Monkey 3 inspected items 26000 times.
== After round 6000 ==
Monkey 0 inspected items 31294 times.
Monkey 1 inspected items 28702 times.
Monkey 2 inspected items 1165 times.
Monkey 3 inspected items 31204 times.
== After round 7000 ==
Monkey 0 inspected items 36508 times.
Monkey 1 inspected items 33488 times.
Monkey 2 inspected items 1360 times.
Monkey 3 inspected items 36400 times.
== After round 8000 ==
Monkey 0 inspected items 41728 times.
Monkey 1 inspected items 38268 times.
Monkey 2 inspected items 1553 times.
Monkey 3 inspected items 41606 times.
== After round 9000 ==
Monkey 0 inspected items 46945 times.
Monkey 1 inspected items 43051 times.
Monkey 2 inspected items 1746 times.
Monkey 3 inspected items 46807 times.
== After round 10000 ==
Monkey 0 inspected items 52166 times.
Monkey 1 inspected items 47830 times.
Monkey 2 inspected items 1938 times.
Monkey 3 inspected items 52013 times.
After 10000 rounds, the two most active monkeys inspected items 52166 and 52013 times. Multiplying these together, the level of monkey business in this situation is now 2713310158
.
Worry levels are no longer divided by three after each item is inspected; you'll need to find another way to keep your worry levels manageable. Starting again from the initial state in your puzzle input, what is the level of monkey business after 10000 rounds?
The less we talk about today the better I’ll feel.
library(tidyverse)
raw_data <- trimws(read_lines("AdventData/day11.txt"))
raw_data <- raw_data[raw_data != ""]
play_game <- function(raw_data, rounds, relief_factor) {
monkeys <- vector('list', length(raw_data)/6)
# Clean the raw data
for(i in seq(0, length(raw_data) - 6, by = 6)){
monkeys[[(i/6) + 1]]$starting_items <- gsub("Starting items: ", "", raw_data[i+2]) %>%
str_split(", ") %>%
unlist() %>%
as.numeric()
monkeys[[(i/6) + 1]]$operation <- gsub("Operation: new = old ", "", raw_data[i+3]) %>%
str_split(" ") %>%
unlist()
monkeys[[(i/6) + 1]]$test <- gsub("Test: divisible by ", "", raw_data[i+4]) %>%
as.numeric()
monkeys[[(i/6) + 1]]$true <- gsub("If true: throw to monkey ", "", raw_data[i+5]) %>%
as.numeric() + 1
monkeys[[(i/6) + 1]]$false <- gsub("If false: throw to monkey ", "", raw_data[i+6]) %>%
as.numeric() + 1
monkeys[[(i/6) + 1]]$inspections <- 0
}
mod <- prod( vapply(monkeys, \(x) as.integer(x$test), FUN.VALUE = 1L) )
for(round in 1:rounds){
for(i in 1:length(monkeys)){
for(item in monkeys[[i]]$starting_items){
monkeys[[i]]$inspections <- monkeys[[i]]$inspections + 1
#Remove item from list
monkeys[[i]]$starting_items <- monkeys[[i]]$starting_items[monkeys[[i]]$starting_items != item]
item <- item %% mod
# Perform operation and reduce worry
item <- floor(eval(parse(text=paste0(item, monkeys[[i]]$operation[1], ifelse(monkeys[[i]]$operation[2] == 'old',
item,
monkeys[[i]]$operation[2]))))/relief_factor)
# move item
if (item %% monkeys[[i]]$test == 0) {
monkeys[[monkeys[[i]]$true]]$starting_items <- c(monkeys[[monkeys[[i]]$true]]$starting_items, item)
} else {
monkeys[[monkeys[[i]]$false]]$starting_items <- c(monkeys[[monkeys[[i]]$false]]$starting_items, item)
}
}
}
}
do.call(rbind, lapply(1:length(monkeys), function(i) tibble(inspections = monkeys[[i]]$inspections))) %>%
arrange(desc(inspections)) %>%
slice(1:2) %>%
pull(inspections) %>%
prod
}
play_game(raw_data, 20, 3)
Day 12
You try contacting the Elves using your handheld device, but the river you're following must be too low to get a decent signal.
You ask the device for a heightmap of the surrounding area (your puzzle input). The heightmap shows the local area from above broken into a grid; the elevation of each square of the grid is given by a single lowercase letter, where a
is the lowest elevation, b
is the next-lowest, and so on up to the highest elevation, z
.
Also included on the heightmap are marks for your current position (S
) and the location that should get the best signal (E
). Your current position (S
) has elevation a
, and the location that should get the best signal (E
) has elevation z
.
You'd like to reach E
, but to save energy, you should do it in as few steps as possible. During each step, you can move exactly one square up, down, left, or right. To avoid needing to get out your climbing gear, the elevation of the destination square can be at most one higher than the elevation of your current square; that is, if your current elevation is m
, you could step to elevation n
, but not to elevation o
. (This also means that the elevation of the destination square can be much lower than the elevation of your current square.)
For example:
Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi
Here, you start in the top-left corner; your goal is near the middle. You could start by moving down or right, but eventually you'll need to head toward the e
at the bottom. From there, you can spiral around to the goal:
v..v<<<<
>v.vv<<^
.>vv>E^^
..v>>>^^
..>>>>>^
In the above diagram, the symbols indicate whether the path exits each square moving up (^
), down (v
), left (<
), or right (>
). The location that should get the best signal is still E
, and .
marks unvisited squares.
This path reaches the goal in 31
steps, the fewest possible.
What is the fewest steps required to move from your current position to the location that should get the best signal?
As you walk up the hill, you suspect that the Elves will want to turn this into a hiking trail. The beginning isn't very scenic, though; perhaps you can find a better starting point.
To maximize exercise while hiking, the trail should start as low as possible: elevation a
. The goal is still the square marked E
. However, the trail should still be direct, taking the fewest steps to reach its goal. So, you'll need to find the shortest path from any square at elevation a
to the square marked E
.
Again consider the example from above:
Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi
Now, there are six choices for starting position (five marked a
, plus the square marked S
that counts as being at elevation a
). If you start at the bottom-left square, you can reach the goal most quickly:
...v<<<<
...vv<<^
...v>E^^
.>v>>>^^
>^>>>>>^
This path reaches the goal in only 29
steps, the fewest possible.
What is the fewest steps required to move starting from any square with elevation a
to the location that should get the best signal?
This took me way longer than I’d like to admit. Definitely over-engineered, I’ve built out a matrix of all the possible destinations and then performed graph functions on them - it means I’ve calculated some edges which we never care about but it still runs quick enough not to worry.
library(tidyverse)
library(igraph)
input <- read_lines("AdventData/day12.txt")
input <- do.call(rbind, strsplit(input, ""))
# Define start and ends + make altitude lookup
start <- paste(unname(which(input == "S", arr.ind = TRUE)), collapse = ',')
end <- paste(unname(which(input == "E", arr.ind = TRUE)), collapse = ',')
altitude_lookup <- c(1:26,1,26)
names(altitude_lookup) <- c(letters,"S","E")
build_edges <- bind_rows(lapply(1:nrow(input), function(i){
bind_rows(lapply(1:ncol(input), function(j) {
moves <- list(U = c(-1, 0), D = c(1, 0), L = c(0, -1), R = c(0, 1))
bind_rows(lapply(moves, function(move){
new_position <- c(i, j) + move
if(!(any(new_position == 0) | any(new_position[1] > nrow(input)) | any(new_position[2] > ncol(input)))) {
if((unname(altitude_lookup[input[new_position[1], new_position[2]]]) - unname(altitude_lookup[input[i,j]])) < 2){
to <- paste0(i,',',j)
from <- paste(new_position, collapse = ',')
data.frame(to = to, from = from)
}
}
}))
}))
}))
graph_data <- cbind(build_edges$to, build_edges$from)
g <- graph_from_data_frame(graph_data, directed=TRUE)
# Part 1 Answer
shortest_paths(g, from = start, to = end, output = "epath")$epath[[1]] %>% length()
# Part 2
possible_starts <- unname(which(input == "a", arr.ind = TRUE))
results <- do.call(rbind, lapply(1:nrow(possible_starts), function(possibility){
shortest_paths(g, from = paste(possible_starts[possibility,], collapse = ','), to = end, output = "epath")$epath[[1]] %>%
length()
}))
min(results[results>0])
Day 13
You climb the hill and again try contacting the Elves. However, you instead receive a signal you weren't expecting: a distress signal.
Your handheld device must still not be working properly; the packets from the distress signal got decoded out of order. You'll need to re-order the list of received packets (your puzzle input) to decode the message.
Your list consists of pairs of packets; pairs are separated by a blank line. You need to identify how many pairs of packets are in the right order.
For example:
[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
Packet data consists of lists and integers. Each list starts with [
, ends with ]
, and contains zero or more comma-separated values (either integers or other lists). Each packet is always a list and appears on its own line.
When comparing two values, the first value is called left and the second value is called right. Then:
- If both values are integers, the lower integer should come first. If the left integer is lower than the right integer, the inputs are in the right order. If the left integer is higher than the right integer, the inputs are not in the right order. Otherwise, the inputs are the same integer; continue checking the next part of the input.
- If both values are lists, compare the first value of each list, then the second value, and so on. If the left list runs out of items first, the inputs are in the right order. If the right list runs out of items first, the inputs are not in the right order. If the lists are the same length and no comparison makes a decision about the order, continue checking the next part of the input.
- If exactly one value is an integer, convert the integer to a list which contains that integer as its only value, then retry the comparison. For example, if comparing
[0,0,0]
and2
, convert the right value to[2]
(a list containing2
); the result is then found by instead comparing[0,0,0]
and[2]
.
Using these rules, you can determine which of the pairs in the example are in the right order:
== Pair 1 ==
- Compare [1,1,3,1,1] vs [1,1,5,1,1]
- Compare 1 vs 1
- Compare 1 vs 1
- Compare 3 vs 5
- Left side is smaller, so inputs are in the right order
== Pair 2 ==
- Compare [[1],[2,3,4]] vs [[1],4]
- Compare [1] vs [1]
- Compare 1 vs 1
- Compare [2,3,4] vs 4
- Mixed types; convert right to [4] and retry comparison
- Compare [2,3,4] vs [4]
- Compare 2 vs 4
- Left side is smaller, so inputs are in the right order
== Pair 3 ==
- Compare [9] vs [[8,7,6]]
- Compare 9 vs [8,7,6]
- Mixed types; convert left to [9] and retry comparison
- Compare [9] vs [8,7,6]
- Compare 9 vs 8
- Right side is smaller, so inputs are not in the right order
== Pair 4 ==
- Compare [[4,4],4,4] vs [[4,4],4,4,4]
- Compare [4,4] vs [4,4]
- Compare 4 vs 4
- Compare 4 vs 4
- Compare 4 vs 4
- Compare 4 vs 4
- Left side ran out of items, so inputs are in the right order
== Pair 5 ==
- Compare [7,7,7,7] vs [7,7,7]
- Compare 7 vs 7
- Compare 7 vs 7
- Compare 7 vs 7
- Right side ran out of items, so inputs are not in the right order
== Pair 6 ==
- Compare [] vs [3]
- Left side ran out of items, so inputs are in the right order
== Pair 7 ==
- Compare [[[]]] vs [[]]
- Compare [[]] vs []
- Right side ran out of items, so inputs are not in the right order
== Pair 8 ==
- Compare [1,[2,[3,[4,[5,6,7]]]],8,9] vs [1,[2,[3,[4,[5,6,0]]]],8,9]
- Compare 1 vs 1
- Compare [2,[3,[4,[5,6,7]]]] vs [2,[3,[4,[5,6,0]]]]
- Compare 2 vs 2
- Compare [3,[4,[5,6,7]]] vs [3,[4,[5,6,0]]]
- Compare 3 vs 3
- Compare [4,[5,6,7]] vs [4,[5,6,0]]
- Compare 4 vs 4
- Compare [5,6,7] vs [5,6,0]
- Compare 5 vs 5
- Compare 6 vs 6
- Compare 7 vs 0
- Right side is smaller, so inputs are not in the right order
What are the indices of the pairs that are already in the right order? (The first pair has index 1, the second pair has index 2, and so on.) In the above example, the pairs in the right order are 1, 2, 4, and 6; the sum of these indices is 13
.
Determine which pairs of packets are already in the right order. What is the sum of the indices of those pairs?
Now, you just need to put all of the packets in the right order. Disregard the blank lines in your list of received packets.
The distress signal protocol also requires that you include two additional divider packets:
[[2]]
[[6]]
Using the same rules as before, organize all packets - the ones in your list of received packets as well as the two divider packets - into the correct order.
For the example above, the result of putting the packets in the correct order is:
[]
[[]]
[[[]]]
[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[1,[2,[3,[4,[5,6,0]]]],8,9]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[[1],4]
[[2]]
[3]
[[4,4],4,4]
[[4,4],4,4,4]
[[6]]
[7,7,7]
[7,7,7,7]
[[8,7,6]]
[9]
Afterward, locate the divider packets. To find the decoder key for this distress signal, you need to determine the indices of the two divider packets and multiply them together. (The first packet is at index 1, the second packet is at index 2, and so on.) In this example, the divider packets are 10th and 14th, and so the decoder key is 140
.
Organize all of the packets into the correct order. What is the decoder key for the distress signal?
More big struggles today, heavily inspired by this contribution and we both seem to have found the same StackOverflow answer for parsing the string.
library(tidyverse)
input <- read_lines("AdventData/day13.txt")
input <- input[input != '']
input <- lapply(seq(1,length(input), by = 2), function(i) list("left" = input[i], "right" = input[i+1]))
parse_string <- function(string){
string %>%
gsub("\\{([^[]+)\\}", "c(\\1)", .) %>%
gsub("([a-zA-Z]\\w+)", "'\\1'", .) %>%
gsub("\\[", "list(", .) %>%
gsub("\\]", ")", .) %>%
parse(text = .) %>%
eval
}
compare_left_right <- function(left, right) {
# check if any list is empty
if(length(left) == 0 && length(right) == 0) return(NA)
else if(length(left) == 0) return(1)
else if(length(right) == 0 ) return(0)
# if the first list entry in both are numbers then compare them
if(typeof(left[[1]]) == 'double' && typeof(right[[1]]) == 'double') {
if(left[[1]] < right[[1]]) return(1)
else if (left[[1]] > right[[1]]) return(0)
else {
left[[1]] <- NULL
right[[1]] <- NULL
return(compare_left_right(left, right))
}
}
# if both elements are lists, unlist them and compare
if(typeof(left[[1]]) == 'list' && typeof(right[[1]]) == 'list'){
result <- compare_left_right(left[[1]], right[[1]])
if(is.na(result)){
left[[1]] <- NULL
right[[1]] <- NULL
return(compare_left_right(left, right))
} else{
return(result)
}
}
#if one is a list and one isnt, add to a list and then retry
if(typeof(left[[1]]) == 'list' && typeof(right[[1]]) == 'double'){
right[[1]] <- list(right[[1]])
return(compare_left_right(left, right))
}
if(typeof(left[[1]]) == 'double' && typeof(right[[1]]) == 'list'){
left[[1]] <- list(left[[1]])
return(compare_left_right(left, right))
}
}
# Part 1
do.call(c,lapply(1:length(input), function(x){
compare_left_right(parse_string(input[[x]]$left), parse_string(input[[x]]$right))
})) %>%
tibble(index = 1:length(input), "correct_order" = .) %>%
filter(correct_order == 1) %>%
pull(index) %>%
sum(.)
# Part 2
input <- read_lines("AdventData/day13.txt")
input <- input[input != '']
position_1 <- do.call(sum, lapply(input, function(left){
compare_left_right(paste_string(left), list(list(2)))
})) + 1
position_2 <- do.call(sum, lapply(input, function(left){
compare_left_right(paste_string(left), list(list(6)))
})) + 2
position_1 * position_2
Day 14
The distress signal leads you to a giant waterfall! Actually, hang on - the signal seems like it's coming from the waterfall itself, and that doesn't make any sense. However, you do notice a little path that leads behind the waterfall.
Correction: the distress signal leads you behind a giant waterfall! There seems to be a large cave system here, and the signal definitely leads further inside.
As you begin to make your way deeper underground, you feel the ground rumble for a moment. Sand begins pouring into the cave! If you don't quickly figure out where the sand is going, you could quickly become trapped!
Fortunately, your familiarity with analyzing the path of falling material will come in handy here. You scan a two-dimensional vertical slice of the cave above you (your puzzle input) and discover that it is mostly air with structures made of rock.
Your scan traces the path of each solid rock structure and reports the x,y
coordinates that form the shape of the path, where x
represents distance to the right and y
represents distance down. Each path appears as a single line of text in your scan. After the first point of each path, each point indicates the end of a straight horizontal or vertical line to be drawn from the previous point. For example:
498,4 -> 498,6 -> 496,6
503,4 -> 502,4 -> 502,9 -> 494,9
This scan means that there are two paths of rock; the first path consists of two straight lines, and the second path consists of three straight lines. (Specifically, the first path consists of a line of rock from 498,4
through 498,6
and another line of rock from 498,6
through 496,6
.)
The sand is pouring into the cave from point 500,0
.
Drawing rock as #
, air as .
, and the source of the sand as +
, this becomes:
4 5 5
9 0 0
4 0 3
0 ......+...
1 ..........
2 ..........
3 ..........
4 ....#...##
5 ....#...#.
6 ..###...#.
7 ........#.
8 ........#.
9 #########.
Sand is produced one unit at a time, and the next unit of sand is not produced until the previous unit of sand comes to rest. A unit of sand is large enough to fill one tile of air in your scan.
A unit of sand always falls down one step if possible. If the tile immediately below is blocked (by rock or sand), the unit of sand attempts to instead move diagonally one step down and to the left. If that tile is blocked, the unit of sand attempts to instead move diagonally one step down and to the right. Sand keeps moving as long as it is able to do so, at each step trying to move down, then down-left, then down-right. If all three possible destinations are blocked, the unit of sand comes to rest and no longer moves, at which point the next unit of sand is created back at the source.
So, drawing sand that has come to rest as o
, the first unit of sand simply falls straight down and then stops:
......+...
..........
..........
..........
....#...##
....#...#.
..###...#.
........#.
......o.#.
#########.
The second unit of sand then falls straight down, lands on the first one, and then comes to rest to its left:
......+...
..........
..........
..........
....#...##
....#...#.
..###...#.
........#.
.....oo.#.
#########.
After a total of five units of sand have come to rest, they form this pattern:
......+...
..........
..........
..........
....#...##
....#...#.
..###...#.
......o.#.
....oooo#.
#########.
After a total of 22 units of sand:
......+...
..........
......o...
.....ooo..
....#ooo##
....#ooo#.
..###ooo#.
....oooo#.
...ooooo#.
#########.
Finally, only two more units of sand can possibly come to rest:
......+...
..........
......o...
.....ooo..
....#ooo##
...o#ooo#.
..###ooo#.
....oooo#.
.o.ooooo#.
#########.
Once all 24
units of sand shown above have come to rest, all further sand flows out the bottom, falling into the endless void. Just for fun, the path any new sand takes before falling forever is shown here with ~
:
.......+...
.......~...
......~o...
.....~ooo..
....~#ooo##
...~o#ooo#.
..~###ooo#.
..~..oooo#.
.~o.ooooo#.
~#########.
~..........
~..........
~..........
Using your scan, simulate the falling sand. How many units of sand come to rest before sand starts flowing into the abyss below?
You realize you misread the scan. There isn't an endless void at the bottom of the scan - there's floor, and you're standing on it!
You don't have time to scan the floor, so assume the floor is an infinite horizontal line with a y
coordinate equal to two plus the highest y
coordinate of any point in your scan.
In the example above, the highest y
coordinate of any point is 9
, and so the floor is at y=11
. (This is as if your scan contained one extra rock path like -infinity,11 -> infinity,11
.) With the added floor, the example above now looks like this:
...........+........
....................
....................
....................
.........#...##.....
.........#...#......
.......###...#......
.............#......
.............#......
.....#########......
....................
<-- etc #################### etc -->
To find somewhere safe to stand, you'll need to simulate falling sand until a unit of sand comes to rest at 500,0
, blocking the source entirely and stopping the flow of sand into the cave. In the example above, the situation finally looks like this after 93
units of sand come to rest:
............o............
...........ooo...........
..........ooooo..........
.........ooooooo.........
........oo#ooo##o........
.......ooo#ooo#ooo.......
......oo###ooo#oooo......
.....oooo.oooo#ooooo.....
....oooooooooo#oooooo....
...ooo#########ooooooo...
..ooooo.......ooooooooo..
#########################
Using your scan, simulate the falling sand until the source of the sand becomes blocked. How many units of sand come to rest?
Today made me feel a whole lot better about the capacity of my brain. Understood how to solve it conceptually after the first read - main issue was I hit a recursion limit in R and decided it’d be quicker to rewrite partly as a while loop.
library(tidyverse)
input <- read_lines("AdventData/day14.txt")
area <- matrix(".", nrow = 1000, ncol = 1000)
# Parse the rock inital positions
lapply(input, function(y){
rock_line <- str_split(y, " -> ")[[1]]
lapply(1:(length(rock_line)-1), function(x){
rock_line_clean <- paste(str_split(rock_line[x], ",")[[1]],
str_split(rock_line[x+1], ",")[[1]], sep = ':')
columns <- eval(parse(text = rock_line_clean[1]))
rows <- eval(parse(text = rock_line_clean[2]))
area[rows + 1, columns] <<- '#'
})
})
find_max_edges <- function(x){max(which(x == '#'))[1]}
row_max <- max(na.omit(apply(area,2,find_max_edges))) + 1
drop_sand <- function(sand_drop_location = c(1, 500), area, part_1 = TRUE){
if(part_1){
# Stop if we fall into the abyss
if(sand_drop_location[1] >= (row_max-1)) {
return(list(area, FALSE))
}
}
# Stop if we cant add any more sand
if(area[sand_drop_location[1], sand_drop_location[2]] != '.'){
return(list(area, FALSE))
}
# Move sand down
new_sand_drop_location <- sand_drop_location + c(1, 0)
if(area[new_sand_drop_location[1], new_sand_drop_location[2]] == '.') {
# nothing blocking it, it moves to the new location
drop_sand(new_sand_drop_location, area, part_1)
} else{
# it is being blocked
left <- new_sand_drop_location + c(0,-1)
right <- new_sand_drop_location + c(0, 1)
# try to move to the left
if(area[left[1], left[2]] == '.') {
drop_sand(left, area, part_1)
} else if (area[right[1], right[2]] == '.') {
drop_sand(right, area, part_1)
} else {
area[sand_drop_location[1], sand_drop_location[2]] <- '+'
return(list(area, TRUE))
}
}
}
#Part 1
new_area <- area
keep_going <- TRUE
while(keep_going){
results <- drop_sand(area = new_area)
new_area <- results[[1]]
keep_going <- results[[2]]
}
sum(new_area == '+')
# Part 2
new_area <- rbind(area[1:row_max,], rep('#', ncol(area)))
keep_going <- TRUE
while(keep_going){
results <- drop_sand(area = new_area, part_1 = FALSE)
new_area <- results[[1]]
keep_going <- results[[2]]
}
cbind(new_area, rep("\n", row_max+1)) %>% t() %>% cat(sep = '')
sum(new_area == '+')
Day 15
You feel the ground rumble again as the distress signal leads you to a large network of subterranean tunnels. You don't have time to search them all, but you don't need to: your pack contains a set of deployable sensors that you imagine were originally built to locate lost Elves.
The sensors aren't very powerful, but that's okay; your handheld device indicates that you're close enough to the source of the distress signal to use them. You pull the emergency sensor system out of your pack, hit the big button on top, and the sensors zoom off down the tunnels.
Once a sensor finds a spot it thinks will give it a good reading, it attaches itself to a hard surface and begins monitoring for the nearest signal source beacon. Sensors and beacons always exist at integer coordinates. Each sensor knows its own position and can determine the position of a beacon precisely; however, sensors can only lock on to the one beacon closest to the sensor as measured by the Manhattan distance. (There is never a tie where two beacons are the same distance to a sensor.)
It doesn't take long for the sensors to report back their positions and closest beacons (your puzzle input). For example:
Sensor at x=2, y=18: closest beacon is at x=-2, y=15
Sensor at x=9, y=16: closest beacon is at x=10, y=16
Sensor at x=13, y=2: closest beacon is at x=15, y=3
Sensor at x=12, y=14: closest beacon is at x=10, y=16
Sensor at x=10, y=20: closest beacon is at x=10, y=16
Sensor at x=14, y=17: closest beacon is at x=10, y=16
Sensor at x=8, y=7: closest beacon is at x=2, y=10
Sensor at x=2, y=0: closest beacon is at x=2, y=10
Sensor at x=0, y=11: closest beacon is at x=2, y=10
Sensor at x=20, y=14: closest beacon is at x=25, y=17
Sensor at x=17, y=20: closest beacon is at x=21, y=22
Sensor at x=16, y=7: closest beacon is at x=15, y=3
Sensor at x=14, y=3: closest beacon is at x=15, y=3
Sensor at x=20, y=1: closest beacon is at x=15, y=3
So, consider the sensor at 2,18
; the closest beacon to it is at -2,15
. For the sensor at 9,16
, the closest beacon to it is at 10,16
.
Drawing sensors as S
and beacons as B
, the above arrangement of sensors and beacons looks like this:
1 1 2 2
0 5 0 5 0 5
0 ....S.......................
1 ......................S.....
2 ...............S............
3 ................SB..........
4 ............................
5 ............................
6 ............................
7 ..........S.......S.........
8 ............................
9 ............................
10 ....B.......................
11 ..S.........................
12 ............................
13 ............................
14 ..............S.......S.....
15 B...........................
16 ...........SB...............
17 ................S..........B
18 ....S.......................
19 ............................
20 ............S......S........
21 ............................
22 .......................B....
This isn't necessarily a comprehensive map of all beacons in the area, though. Because each sensor only identifies its closest beacon, if a sensor detects a beacon, you know there are no other beacons that close or closer to that sensor. There could still be beacons that just happen to not be the closest beacon to any sensor. Consider the sensor at 8,7
:
1 1 2 2
0 5 0 5 0 5
-2 ..........#.................
-1 .........###................
0 ....S...#####...............
1 .......#######........S.....
2 ......#########S............
3 .....###########SB..........
4 ....#############...........
5 ...###############..........
6 ..#################.........
7 .#########S#######S#........
8 ..#################.........
9 ...###############..........
10 ....B############...........
11 ..S..###########............
12 ......#########.............
13 .......#######..............
14 ........#####.S.......S.....
15 B........###................
16 ..........#SB...............
17 ................S..........B
18 ....S.......................
19 ............................
20 ............S......S........
21 ............................
22 .......................B....
This sensor's closest beacon is at 2,10
, and so you know there are no beacons that close or closer (in any positions marked #
).
None of the detected beacons seem to be producing the distress signal, so you'll need to work out where the distress beacon is by working out where it isn't. For now, keep things simple by counting the positions where a beacon cannot possibly be along just a single row.
So, suppose you have an arrangement of beacons and sensors like in the example above and, just in the row where y=10
, you'd like to count the number of positions a beacon cannot possibly exist. The coverage from all sensors near that row looks like this:
1 1 2 2
0 5 0 5 0 5
9 ...#########################...
10 ..####B######################..
11 .###S#############.###########.
In this example, in the row where y=10
, there are 26
positions where a beacon cannot be present.
Consult the report from the sensors you just deployed. In the row where y=2000000
, how many positions cannot contain a beacon?
Not as much time today - only did part 1. Had a go at part 2 but would need to optimise a lot to get it to run in a respectable amount of time.
Update, after a lot of hard work and googling - part 2 solution is now also available.
library(tidyverse)
input <- read_lines("AdventData/day15.txt")
parse_input <- function(input_string){
cleaned_numbers <- gsub("[^0-9\\-]+", " ", input_string) %>%
trimws() %>%
str_split(" ") %>%
`[[`(1) %>%
as.numeric()
tibble(sensor_x = cleaned_numbers[1],
sensor_y = cleaned_numbers[2],
beacon_x = cleaned_numbers[3],
beacon_y = cleaned_numbers[4])
}
input <- bind_rows(lapply(input, parse_input)) %>%
rowwise %>%
mutate(manhattan_distance = sum(abs(c(sensor_x, sensor_y) - c(beacon_x, beacon_y))))
get_unavailable_ranges <- function(xt, yt, manhattan_distance, row){
y_n <- ((-manhattan_distance):manhattan_distance)[which((yt + (-manhattan_distance):manhattan_distance) == row)]
if(!identical(y_n, integer(0))){
xmin = xt + (-(manhattan_distance - abs(y_n)))
xmax = xt + (manhattan_distance - abs(y_n))
tibble(xmin, xmax)
}
}
bind_rows(lapply(1:nrow(input), function(x){
get_unavailable_ranges(input[x,]$sensor_x, input[x,]$sensor_y, input[x,]$manhattan_distance, row = 2000000)
})) %>%
rowwise %>%
mutate(all = list(xmin:xmax)) %>%
pull(all) %>%
unlist() %>%
unique() %>%
length() %>%
`-`(1)
# Part 2
library(tidyverse)
input <- read_lines("AdventData/day15.txt")
parse_input <- function(input_string){
cleaned_numbers <- gsub("[^0-9\\-]+", " ", input_string) %>%
trimws() %>%
str_split(" ") %>%
`[[`(1) %>%
as.numeric()
tibble(sensor_x = cleaned_numbers[1],
sensor_y = cleaned_numbers[2],
beacon_x = cleaned_numbers[3],
beacon_y = cleaned_numbers[4])
}
input <- bind_rows(lapply(input, parse_input)) %>%
rowwise %>%
mutate(manhattan_distance = abs(sensor_x - beacon_x) + abs(sensor_y - beacon_y)) %>%
mutate(b1 = sensor_y + sensor_x + manhattan_distance + 1,
b2 = sensor_y + sensor_x - manhattan_distance - 1,
a1 = sensor_y - sensor_x + manhattan_distance + 1,
a2 = sensor_y - sensor_x - manhattan_distance - 1)
for(a in c(input$a1, input$a2)){
for(b in c(input$b1, input$b2)){
intersection = c((b-a)%/%2, (a+b)%/%2)
if(all(intersection >= 0) & all(intersection <= 4e6)){
checks <- sapply(1:nrow(input), function(sensor){
sum(abs(intersection - c(input[sensor,]$sensor_x, input[sensor,]$sensor_y))) > input[sensor,]$manhattan_distance
})
if(all(checks)){
print(sprintf("%.f",(sum(intersection* c(4000000, 1)))))
break
}
}
}
}
- Posted on:
- December 1, 2022
- Length:
- 83 minute read, 17599 words
- See Also: