Advent of Code: 2022 Day 1 in R

r
advent of code
puzzle
Published

September 7, 2023

Below is my solution for Advent of Code 2022 day 1 in R.

The Brief

Santa’s reindeer typically eat regular reindeer food, but they need a lot of magical energy to deliver presents on Christmas. For that, their favorite snack is a special type of star fruit that only grows deep in the jungle. The Elves have brought you on their annual expedition to the grove where the fruit grows.

To supply enough magical energy, the expedition needs to retrieve a minimum of fifty stars by December 25th. Although the Elves assure you that the grove has plenty of fruit, you decide to grab any fruit you see along the way, just in case.

Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!

The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves’ expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input).

The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they’ve brought with them, one item per line. Each Elf separates their own inventory from the previous Elf’s inventory (if any) by a blank line.

For example, suppose the Elves finish writing their items’ Calories and end up with the following list:

1000
2000
3000

4000

5000
6000

7000
8000
9000

10000

This list represents the Calories of the food carried by five Elves: - 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. - The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories. - The fifth Elf is carrying one food item with 10000 Calories.

Part 1

In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they’d like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf).

Find the Elf carrying the most calories. How many total Calories is that Elf carrying?

Read Input

The first part of any Advent of Code puzzle is reading in the input file. I always copy the example input given to use as a test case. That’s test_input.txt. I have also copied my actual puzzle input into input.txt.

In this case, we need to read the lines of the input file and find a way to work with the data structure in R. Just reading in the data is very easy:

read_input <- function(file) {
  as.numeric(readLines(file))
}

That will give us a numeric vector where each line in the file is an element in the vector, and the empty lines that separate the elves will be NA. This will actually make it pretty easy to iterate through because we can use is.na() to determine when we’re moving to a new Elf.

Solve

The solution is relatively straightforward. We keep a running total of Calories for each Elf, then when we get to the end of that Elf’s values we check to see if that Elf’s total is higher than the highest we’ve yet seen.

part_1 <- function(input_data) {
1  highest_total <- 0
  running_total <- 0
2  for (i in input_data) {
3    if (is.na(i)) {
      if (running_total > highest_total) {
        highest_total <- running_total
      }
4      running_total <- 0
5      next
    }
6    running_total <- running_total + i
  }
7  if (running_total > highest_total) {
    highest_total <- running_total
  }
  highest_total
}
1
Initialize variables to use in the loop
2
Iterate over each element in input_data
3
If is.na(i) we know that we’ve reached the end of the Elf’s values, so we can check the running total against the highest total that we’ve seen
4
Re-set the running_total variable to 0 so that we can start clean with the next Elf
5
We use next to move onto the next iteration of the loop so that we don’t try to do calculations on NA
6
If !is.na(i) then we just add the current element to the running total
7
Finally, we know that checking is.na(i) will not capture the elements for the last Elf in the input. So after the loop, we check one last time if running_total > highest_total, just to check for that last Elf.

We need to run this with the example data to make sure we come up with 24,000:

test_data <- read_input("test_input.txt")
part_1(test_data)
[1] 24000

Success! Now we try it on the real data.

real_data <- read_input("input.txt")
part_1(real_data)
[1] 71924

Advent of Code tells me that’s correct!

Part 2

By the time you calculate the answer to the Elves’ question, they’ve already realized that the Elf carrying the most Calories of food might eventually run out of snacks.

To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups.

In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves is 45000.

Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?

Solve

This one is a bit trickier because we need to keep track of all of the Elves’ totals and take the top three once we’ve counted them all up. We can use the same input data as before and we don’t need to mess with the function to read it in. What I will do now, instead of keeping track of the single highest total, is just populate a vector with all of the totals, sort it, and then take the three highest values. I can figure out the size of vector that I need by getting the number of NAs and adding one – there is an NA between every Elf, but none after the last one, so that has to be added on.

part_2 <- function(input_data) {
1  elf_totals <- numeric(sum(is.na(input_data)) + 1)
  
2  current_elf <- 1
  running_total <- 0
3  for (i in seq_along(input_data)) {
4    if (i == length(input_data)) {
      running_total <- running_total + input_data[i]
      elf_totals[current_elf] <- running_total
    }
5    if (is.na(input_data[i])) {
      elf_totals[current_elf] <- running_total
      running_total <- 0
      current_elf <- current_elf + 1
      next
    }
6    running_total <- running_total + input_data[i]
  }
7  sum(sort(elf_totals, decreasing = TRUE)[1:3])
}
1
Pre-allocate the vector that will contain the Elves’ totals
2
Initialize variables
3
Iterate through the input data
4
If we’re at the end of the data, we need to update the running_total and tack that onto elf_totals. We have to do this check separately from the is.na() check because the data ends with the last Elve’s last snack, not NA. In retrospect, I could’ve potentially simplified the code by adding NA to the end of the input data vector, but checking manually for the end of the vector isn’t particularly hard or confusing, so I just stick with that.
5
If the current value of the vector is NA, we need to populate the elf_totals vector with the running_total that we’ve been adding up. We then reset running_total to 0 and increment the current_elf count, before continuing in the loop.
6
Add the current value in the data vector onto the running_total
7
Finally, we sort the elf_totals vector, specifying decreasing = TRUE, take the first three elements, and then return the sum.

Checking this on the example data, making sure it returns 45,000:

part_2(test_data)
[1] 45000

Good! And now the real data:

part_2(real_data)
[1] 210406

Which Advent of Code tells me is correct.

So that’s all there is to it! Happy coding!