Day 6

Author

Julia Romanowska

Data

This is the stream of characters that needs to be proceed in sequential manner to find the start-of-packet marker. This is indicated by a sequence where all four characters are different.

(
  stream_input <- scan(
    here("DATA", "2022", "input_day_06.txt"),
    what = "character"
    ) %>%
    strsplit(split = "", fixed = TRUE) %>%
    unlist()
) %>% head(10)
 [1] "c" "v" "t" "v" "b" "v" "f" "b" "v" "f"

Part one

Functions

I will need to check at each item:

  • whether there are enough characters to create a marker (i.e., min.4) and
  • whether all last 4 are different
pop_first <- function(cur_read){
  return(cur_read[-1])
}

push_last <- function(cur_read, new_char){
  return(c(cur_read, new_char))
}

update_cur_read <- function(cur_read, new_char){
  new_read <- pop_first(cur_read)
  new_read <- push_last(new_read, new_char)
  return(new_read)
}

check_uniqueness <- function(cur_read){
  n_unique <- length(unique(cur_read))
  return(n_unique == length(cur_read))
}

Process input

cur_position <- 4
cur_read <- stream_input[1:cur_position]
while (!check_uniqueness(cur_read) | cur_position == length(stream_input)) {
  cur_position <- cur_position + 1
  new_char <- stream_input[cur_position]
  
  cur_read <<- update_cur_read(cur_read, new_char)
}

The number of characters to be processed before the first start-of-packet marker is detected is 1093! 🥳

Part two

Detect start-of-the-message marker

The start-of-the-message marker consists of 14 distinct characters!

cur_position <- 14
cur_read <- stream_input[1:cur_position]
while (!check_uniqueness(cur_read) | cur_position == length(stream_input)) {
  cur_position <- cur_position + 1
  new_char <- stream_input[cur_position]
  
  cur_read <<- update_cur_read(cur_read, new_char)
}

The number of characters to be processed before the first start-of-message marker is detected is 3534! 🥳