Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

r

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')
like image 707
RoyalTS Avatar asked Sep 01 '25 00:09

RoyalTS


1 Answers

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"
like image 105
Ben Bolker Avatar answered Sep 02 '25 17:09

Ben Bolker