Day 6

Advent of Code: Worked Solutions

About
Date

December 6, 2022

Setup

# Libraries
library(tidyverse)

# Read input from file
input <- read_lines("../input/day06.txt") |>
  str_split_1("") |>
  enframe(name = "idx", value = "char")

Part 1

find_marker <- function(df, marker_length) {
  df |> 
    # Construct sequences of next n chars and count # of unique chars in each
    transmute(
      marker_idx = idx + marker_length - 1,
      char_seq = reduce(
        .x = map(0:(marker_length - 1), ~ lead(char, n = .x)),
        .f = str_c
      ),
      n_unique = map_int(
        char_seq,
        ~ .x |>
          str_split("") |>
          unlist() |>
          unique() |>
          length()
      )
    ) |>

    # Extract first instance where all n chars are unique
    filter(n_unique == marker_length) |>
    pull(marker_idx) |>
    min()
}
find_marker(input, marker_length = 4)
[1] 1802

Part 2

find_marker(input, marker_length = 14)
[1] 3551