-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday-13.R
More file actions
74 lines (62 loc) · 1.89 KB
/
day-13.R
File metadata and controls
74 lines (62 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Execute all folding instructions on a given sheet of paper
fold_all <- function(m, folds) {
for (instruction in folds)
m <- fold_paper(m, instruction)
m
}
# Make the generated ASCII image of the code readable on terminal
decode_day13 <- function(m) {
lines <- sapply(
seq_len(nrow(m)),
\(i) paste(as.integer(m[i, ]), collapse = "")
) |>
(\(x) gsub("1", "#", x))() |>
(\(x) gsub("0", " ", x))()
lines
}
# Execute one folding instruction
fold_paper <- function(m, instruction) {
axis <- instruction[[1]]
position <- instruction[[2]]
if (axis == "y") {
rows <- list(1:(position - 1), (position + 1):nrow(m))
cols <- list(1:ncol(m), 1:ncol(m))
} else {
rows <- list(1:nrow(m), 1:nrow(m))
cols <- list(1:(position - 1), (position + 1):ncol(m))
}
half1 <- m[rows[[1]], cols[[1]]]
half2 <- m[rows[[2]], cols[[2]]] |> flip_paper(axis)
half1 | half2
}
# Read the input file, return a list with a dotted sheet of paper
# and the series of folding instructions
read_day13 <- function(file) {
lines <- file |> readLines()
blank <- which(lines == "")
dots <- lines[1:(blank - 1)] |> strsplit(",") |> lapply(as.integer)
folds <- lines[(blank + 1):length(lines)] |>
strsplit(" ") |>
lapply(function(x) {
tokens <- strsplit(x[3], "=")[[1]]
list(tokens[1], as.integer(tokens[2]) + 1)
})
# set up dots on the paper
xdim <- max(sapply(dots, `[[`, 1)) + 1
ydim <- max(sapply(dots, `[[`, 2)) + 1
paper <- matrix(FALSE, nrow = ydim, ncol = xdim)
for (dot in dots) {
paper[dot[2] + 1, dot[1] + 1] <- TRUE
}
list(paper = paper, folds = folds)
}
# Flip either the bottom half of the paper up, or the right half of
# the paper to the left
flip_paper <- function(m, axis) {
if (axis == "x")
m[, rev(seq_len(ncol(m)))]
else if (axis == "y")
m[rev(seq_len(nrow(m))), ]
else
stop("Invalid axis '", axis, "'", call. = FALSE)
}