03: Spiral Memory

library(mistlecode)
To install `mistlecode` yourself, run `devtools::install_github('guslipkin/mistlecode')`.

 Also loading:  cipheR data.table dplyr purrr slider stringr tidyverse glue
input <- 265149

Part 1

grid_dim <- ceiling(sqrt(input))

diff <- (grid_dim ^ 2) - input

side <- case_when(
  diff < grid_dim ~ "bottom",
  diff >= grid_dim & diff < grid_dim * 2 ~ "left",
  diff >= grid_dim * 2 & diff < grid_dim * 3 ~ "top",
  diff >= grid_dim * 3 & diff < grid_dim * 4 ~ "right",
)

mid <- ((grid_dim - 1) / 2)
abs((grid_dim - diff) - mid) + mid - 1
[1] 438

Part 2

I don’t know why I struggled. This was actually kinda fun. Getting the logic for the movements was odd.

m <- matrix(1, 1, 1)
point = list(x = 1, y = 1)
repeat {
  if (point$y == nrow(m) & point$x == ncol(m)) {
    tmp <- matrix(NA_integer_, ncol(m) + 2, nrow(m) + 2)
    tmp[2:(nrow(tmp) - 1), 2:(ncol(tmp) - 1)] <- m
    m <- tmp
    point$x <- point$x + 2
    point$y <- point$y + 1
  } else if (point$x == ncol(m) & point$y != 1) {
    point$y <- point$y - 1
  } else if (point$x <= ncol(m) & point$y == 1 & point$x - 1 >= 1) {
    point$x <- point$x - 1
  } else if (point$x == 1 & point$y >= 1 & point$y + 1 <= nrow(m)) {
    point$y <- point$y + 1
  } else {
    point$x <- point$x + 1
  }
  m[point$y, point$x] <-
    sum(get_adjacent_values(point$y, point$x, m), na.rm = TRUE)
  # print(m)
  if (m[point$y, point$x] > input) break
}
max(m, na.rm = TRUE)
[1] 266330