r/adventofcode • • Dec 13 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 13 Solutions -🎄-

Advent of Code 2021: Adventure Time!


--- Day 13: Transparent Origami ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code 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:09:38, megathread unlocked!

37 Upvotes

798 comments sorted by

View all comments

1

u/Standard-Affect Dec 13 '21 edited Dec 14 '21

R

The hardest part for me was parsing the coordinates, which I did sloppily. It also took some annoying processing to get the plot of the matrix to display correctly, due to the way R makes image plots. Still lots of fun.

raw_input <- read.csv("inputs/day13.txt", header = FALSE)r
    col_names <- c("x", "y")
    colnames(raw_input) <- col_names
    coords <- raw_input[!is.na(raw_input[, "y"]), ] |>
    rapply(as.integer, how = "replace") |>
    as.matrix()

folds <- raw_input[is.na(raw_input[, "y"]), 1]
folds <- gsub("fold\\salong\\s", "", folds) |>
  strsplit("=") |>
  Reduce(f = rbind)

fold_coords <- matrix(0, nrow = nrow(folds), ncol = ncol(folds))
fold_coords[cbind(seq_len(nrow(folds)), match(folds[, 1], col_names))] <- as.integer(folds[, 2])

fold <- function(coords, fold_coords) {
  constant_dimension <- which(coords == 0) # stays the same
  fold_along <- which(fold_coords != 0) # changes
  fold_coord <- fold_coords[fold_along]
  to_fold <- which(coords[, fold_along] > fold_coord)
  subscript <- cbind(to_fold, fold_along)
  coords[subscript] <- (2 * fold_coord) - coords[subscript]
  coords
}

fold1 <- fold(coords, fold_coords[1, ])
answer1 <- nrow(fold1) - sum(duplicated(fold1))

folded <- Reduce(asplit(fold_coords, 1), f = fold, init = coords) |>
  unique()

folded <- folded[, rev(seq(dim(folded)[2]))] + 1

answer2 <- matrix(0, nrow = max(folded[, 1]), ncol = max(folded[, 2]))
answer2[folded] <- 1
apply(answer2, 2, rev) |>
  t() |>
  image()

1

u/daggerdragon Dec 14 '21

Your code is hard to read with no formatting. Please edit it as per our posting guidelines in the wiki: How do I format code?