All strings of length k that can be formed from a set of n characters

This question has been asked for other languages, but I'm looking for the most idiomatic way to find all length strings k

that can be formed from a character set n

in R

Example input and output:

input <- c('a', 'b')

output <- c('aa', 'ab', 'ba', 'bb')

      

+3


source to share


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


An adaptation of AK88's answer, outer

can be used for arbitrary values k

, although this is not necessarily the most efficient solution:



input <- c('a', 'b')
k = 5
perms = input
for (i in 2:k) {
    perms = outer(perms, input, paste, sep="")
}
result = as.vector(perms)

      

+2


source


m <- outer(input, input, paste, sep="")
output = as.vector(m)

## "aa" "ba" "ab" "bb"

      

+1


source


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







All Articles