This question has been asked for other languages but I'm looking for the most idiomatic way to find all strings of length k
that can be formed from a set of n
characters in R
Example input and output:
input <- c('a', 'b')
output <- c('aa', 'ab', 'ba', 'bb')
A little more complicated than I'd like. I think outer()
only works for n=2
. combn
doesn't include repeats.
allcomb <- function(input = c('a', 'b'), n=2) {
args <- rep(list(input),n)
gr <- do.call(expand.grid,args)
return(do.call(paste0,gr))
}
Thanks to @thelatemail for improvements ...
allcomb(n=4)
## [1] "aaaa" "baaa" "abaa" "bbaa" "aaba" "baba" "abba"
## [8] "bbba" "aaab" "baab" "abab" "bbab" "aabb" "babb"
## [15] "abbb" "bbbb"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With