Advent of Code: 2022 Day 6 in R

r
advent of code
puzzle
Published

September 11, 2023

Day 6: Tuning Trouble

See the puzzle instructions here.

Part 1

This puzzle is a bit unique in that it give us 5 distinct test cases
- test_input_1.txt
- test_input_2.txt
- test_input_3.txt
- test_input_4.txt
- test_input_5.txt

In addition to input.txt.

I think this will be fairly straightforward. We read in the data as a single long character string, then split it into a vector of individual characters. We iterate through that vector looking ahead at the next four characters. The first time that length(unique(vec)) == 4, we have found the first start-of-package marker.

part_1 <- function(file) {
  data <- readLines(file)
  char_vector <- strsplit(data, "")[[1]]
  for (i in seq_along(char_vector)) {
    four_chars <- char_vector[i:(i + 3)]
    if (length(unique(four_chars)) == 4) {
      return(i + 3)
    }
  }
}
part_1("test_input_1.txt") == 7
[1] TRUE
part_1("test_input_2.txt") == 5
[1] TRUE
part_1("test_input_3.txt") == 6
[1] TRUE
part_1("test_input_4.txt") == 10
[1] TRUE
part_1("test_input_5.txt") == 11
[1] TRUE

The examples look good. Now for the real data:

part_1("input.txt")
[1] 1582

Success!

Part 2

Now for part 2.

This should be the same, just switching out 14 for 4 when checking length(unique(four_chars)).

part_2 <- function(file) {
  data <- readLines(file)
  char_vector <- strsplit(data, "")[[1]]
  for (i in seq_along(char_vector)) {
    four_chars <- char_vector[i:(i + 13)]
    if (length(unique(four_chars)) == 14) {
      return(i + 13)
    }
  }
}
part_2("test_input_1.txt") == 19
[1] TRUE
part_2("test_input_2.txt") == 23
[1] TRUE
part_2("test_input_3.txt") == 23
[1] TRUE
part_2("test_input_4.txt") == 29
[1] TRUE
part_2("test_input_5.txt") == 26
[1] TRUE

All good. Now for the real data:

part_2("input.txt")
[1] 3588

Correct! This was a very easy challenge to do in R. It’s possible that it would be more difficult in other languages. For example, in Go we would not have access to a function like unique() but would instead have to manually compare values or create a map with the characters in the vector to check for uniqueness. Regardless, this was straightforward to the point of triviality in R.

You can find all of my Advent of Code solutions on GitHub.