1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
GetWords <- function(n, k, alphabet = c('a', 'b')) {
## Get the n-nth words with k letters using a given alphabet.
stopifnot( n >= 0, length(k) == 1, k > 0, length(alphabet) > 0)
m <- length(alphabet);
## Get a single word
GetWord <- function(x) {
## Create an empty word filled with '0'
word <- rep(alphabet[1], k)
i <- k
## Convert the number 'x' to base 'm'
while(x > 0) {
word[i] <- alphabet[(x %% m)+1]
i <- i - 1;
x <- x %/% m
}
return(paste(word, collapse =''))
}
## Get all words (vectorized loop)
sapply(n, GetWord)
}
## Convert to binary
GetWords(1:10, k=4)
## Convert to decimal
GetWords(5:10, k=4, alphabet=0:9) |