── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0 ✔ purrr 0.3.5
✔ tibble 3.1.8 ✔ dplyr 1.0.10
✔ tidyr 1.2.1 ✔ stringr 1.5.0
✔ readr 2.1.3 ✔ forcats 0.5.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
Attaching package: 'data.table'
The following objects are masked from 'package:dplyr':
between, first, last
The following object is masked from 'package:purrr':
transpose
dt <- unlist (strsplit (readLines ("input.txt" ), "" ))
This looks easy. Oh wait. I totally misread the problem…
do_part <- function (part) {
part <- part - 1
get_vec <- function (vec, place) {
if (place == 0 ) { return (vec)}
c (vec[- 1 : (- place)], rep (NA , place))
}
lapply (0 : part, function (x) {
get_vec (dt, x)
}) |>
data.frame () |>
` colnames<- ` (paste0 ("X" , 1 : part)) %>%
apply (1 , function (x) {
paste0 (x, collapse = "" )
}) |>
sapply (function (x) {
max (table (strsplit (x, "" )))
}) -> tmp
(which (tmp == 1 ) + part)[1 ]
}
Part 1
Hardcoding everything will bite me in the butt later probably. Ultimately not too bad in hindsight.
data.frame ("w" = dt,
"x" = c (dt[- 1 ], NA ),
"y" = c (dt[- 1 :- 2 ], NA , NA ),
"z" = c (dt[- 1 :- 3 ], NA , NA , NA )) |>
mutate (marker = paste0 (w, x, y, z, sep = "" )) |>
apply (1 , function (x) {
max (table (strsplit (x["marker" ], "" )))
}) -> tmp
(which (tmp == 1 ) + 3 )[1 ]
Part 2
Well, well, well. Hardcoding is never a good move. Took a bit of time to get it figured out, but I got there in the end.
get_vec <- function (vec, place) {
if (place == 0 ) { return (vec) }
c (vec[- 1 : (- place)], rep (NA , place))
}
lapply (0 : 13 , function (x) {
get_vec (dt, x)
}) |>
data.frame () |>
` colnames<- ` (paste0 ("X" , 1 : 14 )) %>%
apply (1 , function (x) {
paste0 (x, collapse = "" )
}) |>
sapply (function (x) {
max (table (strsplit (x, "" )))
}) -> tmp
(which (tmp == 1 ) + 13 )[1 ]