All strings of length k that can be formed from a set of n characters
4 answers
A little more difficult than we would like. I think it outer()
only works for n=2
. combn
does not include repetitions.
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 the improvements ...
allcomb(n=4)
## [1] "aaaa" "baaa" "abaa" "bbaa" "aaba" "baba" "abba"
## [8] "bbba" "aaab" "baab" "abab" "bbab" "aabb" "babb"
## [15] "abbb" "bbbb"
+5
source to share
I'm not proud of the way it looks, but it works ...
allcombs <- function(x, k) { apply(expand.grid(split(t(replicate(k, x)), seq_len(k))), 1, paste, collapse = "") } allcombs(letters[1:2], 2) #> [1] "aa" "ba" "ab" "bb" allcombs(letters[1:2], 4) #> [1] "aaaa" "baaa" "abaa" "bbaa" "aaba" "baba" "abba" "bbba" "aaab" "baab" #> [11] "abab" "bbab" "aabb" "babb" "abbb" "bbbb"
+1
source to share