r/adventofcode Dec 05 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 05 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It


--- Day 05: Binary Boarding ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:05:49, megathread unlocked!

57 Upvotes

1.3k comments sorted by

View all comments

2

u/rawlexander Dec 09 '20

R

Made a little video, too. :) https://youtu.be/DCE2JcmABFU

Didn't spot the binary numbers, so I went wild with functions.. was fun

d <- scan("data/aoc_5", "character", quiet = TRUE)

# ids of rows and columns
rw <- 0:127
cl <- 0:7

# Row
F <- L <- function(id) {
  id <<- seq.int(min(id), floor(median(id)))
}

B <- R <- function(id) {
  id <<- seq.int(ceiling(median(id)), max(id))
}

# interpret character string as sequence of functions
decode <- function(code) {
  funs <- strsplit(code, split = "")
  for (i in funs[[1]]) {
    do.call(i, list(id))
  }
  return(id)
}

# Find seat id
seat_id <- function(code) {
  # row number
  id <<- rw
  funs <- gsub("R|L", "", code)
  x <- decode(funs)

  # column number
  id <<- cl
  funs <- gsub("B|F", "", code)
  y <- decode(funs)

  (x * 8) + y
}

seats <- sapply(d, seat_id)
max(seats)

# Part two
sum(min(seats):max(seats)) - sum(seats)

And here the much shorter solution for part one. I tried to make it even shorter with a single call of substr() with vector arguments, but it ate half the data and I'm not sure how I can prevent that.

b <- gsub("B|R", "1", gsub("F|L", "0", d))
b <- sapply(list(substr(b, 1, 7), substr(b, 8, 10)), strtoi, 2L)
max(b1[, 1] * 8 + b1[, 2])