Skip to content

Instantly share code, notes, and snippets.

@jrosell
Last active December 17, 2024 14:51
Show Gist options
  • Save jrosell/5a7bff297e5d3aab9e6ce20d274cb636 to your computer and use it in GitHub Desktop.
Save jrosell/5a7bff297e5d3aab9e6ce20d274cb636 to your computer and use it in GitHub Desktop.
# Level 2
minimal_character_positions <- \(s) {
max_len <- max(nchar(s))
for (i in seq_len(max_len)) {
for (indices in combn(seq_len(max_len), i, simplify = FALSE)) {
char_vectors <-
purrr::map(s, \(str, idx = indices) {
purrr::map_chr(idx, \(ii) {
if (ii <= nchar(str)) substr(str, ii, ii) else NA
})
})
if (length(unique(char_vectors)) == length(char_vectors)) {
return(indices)
}
}
}
return(NULL)
}
# Is it working?
test_cases <- rlang::list2(
list(input = c("apple", "app", "applies"), expected = c(5L)),
list(input = c("cat", "car", "bat"), expected = c(1L, 3L)),
list(input = c("apple", "banana", "cherry"), expected = c(1L)),
list(input = c("ape", "bat", "cap", "zap"), expected = c(1L)),
list(input = c("cat", "car", "bat", "pat"), expected = c(1L, 3L)),
list(input = c("apple"), expected = c(1L)),
list(input = c("cat", "car", "bat", "batman"), expected = c(1L, 3L, 4L)),
list(input = c("a", "b", "c", "d"), expected = c(1L)),
list(input = c("apple", "", "banana"), expected = c(1L)),
list(input = c("apple", "app", "appl"), expected = c(4L, 5L))
)
for (i in seq_along(test_cases)) {
result <- minimal_character_positions(test_cases[[i]]$input)
expected <- test_cases[[i]]$expected
if (!identical(result, expected)) {
stop(paste("Test case", i, "failed. Expected:", toString(expected), "but got:", toString(result)))
} else {
cat(paste("Test case", i, "passed.", '\n'))
}
}
minimal_prefix_length <- function(strings) {
max_len <- max(nchar(strings))
for (prefix_len in seq_len(max_len)) {
env <- new.env(hash = TRUE)
collision <- FALSE
for (string in strings) {
prefix <- substr(string, 1, prefix_len)
if (exists(prefix, envir = env)) {
collision <- TRUE
break
} else {
assign(prefix, TRUE, envir = env)
}
}
if (!collision) {
return(prefix_len)
}
}
return(max_len)
}
s <- c("apple", "app", "aptitude")
minimal_prefix_length(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment