2021 Day 20

Author

Nathan Moore

— Day 20: Trench Map —

We need to map the ocean floor with an image enhancement algorithm.

Start with the original input image and apply the image enhancement algorithm twice, being careful to account for the infinite size of the images. How many pixels are lit in the resulting image?

library(tidyverse)

my_file <- here::here("2021", "data-2021-20.txt")
x <- readLines(my_file)

Function

get_pixel <- function(sq) {
  px = rep(",", 9)

  for (c in seq(3)) {
    for (d in seq(3)) {
      # rr = d + 3 * (c - 1)
      px[d + 3 * (c - 1)] = sq[c, d]
    }
  }

  # tt = str_replace_all(px, c("\\." = "0", "#" = "1"))
  tt = paste0(str_replace_all(px, c("\\." = "0", "#" = "1")), collapse = "")
  # print(tt)
  return(algo[strtoi(tt, 2) + 1])
}

Loop through the algorithm

# setup for algorithm and image
algo = unlist(strsplit(x[1], ""))
init = unlist(str_split_fixed(x[3:102], "", 100))

img = array(".", c(140, 140))
img[21:120, 21:120] = init

# capture the output
img_n = array(".", c(140, 140))
n = 2

# loop through img
for (z in seq(2)) {
    for (j in seq(3, nrow(img) - 3)) {
        for (k in seq(3, nrow(img) - 3)) {
            sq = img[(j-1):(j+1), (k-1):(k+1)]
            px = get_pixel(sq)
            # print(px)
            img_n[j, k] = get_pixel(sq)
        }
    }
    img = img_n[3:(nrow(img) - 3), 3:(ncol(img) - 3)]
    img_n = img
}

sum(img == "#")
[1] 5231

— Part Two —

Start again with the original input image and apply the image enhancement algorithm 50 times. How many pixels are lit in the resulting image?

# setup for algorithm and image
algo = unlist(strsplit(x[1], ""))
init = unlist(str_split_fixed(x[3:102], "", 100))

img = array(".", c(250, 250))
img[76:175, 76:175] = init

# capture the output
n = 2

# loop through img
for (z in seq(n)) {
    print(z)
    if (n %% 2 == 0) {
        img_n = array(".", c(250, 250))
    } else {
        img_n = array("#", c(250, 250))
    }

    for (j in seq(3, 247)) {
        for (k in seq(3, 247)) {
              sq = img[(j-1):(j+1), (k-1):(k+1)]
              px = get_pixel(sq)
              # print(px)
              img_n[j, k] = get_pixel(sq)
        }
    }
    img = img_n
}
[1] 1
[1] 2
sum(img == "#")
[1] 5964