To install `mistlecode` yourself, run `devtools::install_github('guslipkin/mistlecode')`.
Also loading: cipheR data.table dplyr purrr slider stringr tidyverse glue
11: Corporate Policy
Part 1
I struggled for so long with some half-baked quasi-recursive solution that worked on one of the test inputs. I eventually realized that I needed my replacement function to be recursive (I was working with string indexes before) and then it all fell into place. Not my fastest computationally, but it gets the job done.
check_consecutive <- function(x) {
x <- paste0(x, collapse = "")
letters |>
runner(k = 3, f = paste0, collapse = "") |>
tail(-2) |>
map_lgl(~ str_detect(x, .x)) |>
any()
}
check_confusing <- function(x) { !any(c("i", "o", "l") %in% x) }
check_pairs <- function(x) {
x <-
data.frame(
"a" = x,
"b" = lead(x)
) |>
filter(a == b) |>
group_by(a, b) |>
count() |>
nrow()
return(x >= 2)
}
check <- function(x) {
return(
check_consecutive(x) &
check_confusing(x) &
check_pairs(x)
)
}
no_iol <- letters[!(letters %in% c("i", "o", "l"))]
replace <- function(x, pos) {
l <- which(no_iol == x[pos]) + 1
if (l > length(no_iol)) {
x[pos] <- "a"
x <- replace(x, pos - 1)
} else {
x[pos] <- no_iol[l]
}
return(x)
}
split_dt <- str_split(dt, "")[[1]]
repeat {
if (check(split_dt)) { break }
split_dt <- replace(split_dt, length(split_dt))
}
paste0(split_dt, collapse = "")
[1] "hxbxxyzz"
Part 2
Hmmm. I suppose my solution from part 1 wouldn’t work right away. That would be too easy. I could just say that’s no longer a valid solution then it’ll keep going. Kinda dumb but it should work.
It’s me. I’m back. It was taking too long. I think I can speed this up just by thinking about it. If xx
changes to xy
, that whole branch becomes invalid no matter what comes after because it won’t have a sequence available. Same with yy
or zz
. So that means that b
has to increase to c
. Here we have some more options. In fact, we have a whole alphabet’s worth. We want to minimize the value so let’s go with a
. Same for the next character. Now we only have three spots left and we need to complete our sequence of three letters and get another double. If we do bbc
, we don’t have the sequence so we have to do bcc
to complete the sequence and get the last double.