Advent of Code 2020 Day 5

Author

Nathan Moore

— Day 5: Binary Boarding —

You dropped your boarding pass, and now have to find your seat.

As a sanity check, look through your list of boarding passes. What is the highest seat ID on a boarding pass?

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.6
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.1     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.2.0     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
bp <- read.delim("data-2020-05.txt", header = FALSE)

# conversions for letters to binary
fm = c("F", "B", "L", "R") 
to = c("0", "1", "0", "1")

named_v = c("F" = "0", "B" = "1", "L" = "0", "R" = "1")

Create a dataframe and a function and work out the max.

# function to convert, since we have to do four replacements
convert_bp <- function(bpx) {
  for (x in seq_along(fm)) {
    bpx = str_replace_all(bpx, fm[x], to[x])
  }
  return(bpx)
}

# mutate seems like the best way to do this
# we can also use many replacements in one function
bp_bin <- bp %>% 
  mutate(
    # bin = convert_bp_2(V1), 
    bin = str_replace_all(V1, named_v),
    row = strtoi(str_sub(bin, end = 7), base = 2), 
    col = strtoi(str_sub(bin, start = 8), base = 2), 
    id = row * 8 + col
  )

# max is part one answer
max_id <- max(bp_bin$id)  
min_id <- min(bp_bin$id)

max_id
[1] 970

— Part Two —

You have to find your seat number, quick!

What is the ID of your seat?

# possible seats from min to max
bp_seq = seq(from = min_id, to = max_id)

# part two answer
setdiff(bp_seq, bp_bin$id)
[1] 587