This approach works nicely, even though it has little to do with your original function. It is not perfect, but can be generalized to any amount of letters easily. This version can handle any number up to 26+26^2+26^3+26^4+26^5+26^6 = 321272406
, i.e. up to 6 letters.
First, we define a function that determines the number of letters and adjusts the number, to remove the combinations with a lower number of letters.
Consider for example the number 702
. It is "ZZ" in letters, but there are only 26^2 = 676
possible combinations with two letters - hence, we have to subtract the 26
single letters beforehand for the "adjusted number". Now, if the adjusted number is, e.g. 1 and we have 5 letters, the resulting word is "AAAAA", for 2 it is "AAAAB" and so on.
Here are the functions:
checknum <- function(num) {
adnum<-num; #adjusted number
n_lett<-1; #number of letters
if(log(adnum,base=26) > 1) {adnum<-adnum-26; n_lett<-2}
if(log(adnum,base=26) > 2) {adnum<-adnum-26^2; n_lett<-3}
if(log(adnum,base=26) > 3) {adnum<-adnum-26^3; n_lett<-4}
if(log(adnum,base=26) > 4) {adnum<-adnum-26^4; n_lett<-5}
if(log(adnum,base=26) > 5) {adnum<-adnum-26^5; n_lett<-6}
return(list(adnum=adnum,n_lett=n_lett))
} #this function can be adjusted for more letters or maybe improved in its form
applett2 <- function(num) {
n_lett<-checknum(num)$n_lett;
adnum<-checknum(num)$adnum-1;
out<-c(rep(1,n_lett));
for(i in 1:n_lett) {
out[i]<-(floor(adnum/(26^(n_lett-i)))%%26)+1;
}
return(paste(LETTERS[out],collapse=""))
} #main function that creates the letters
applett2(26+26^2+26^3+26^4)
# "ZZZZ"
applett2(1234567)
# "BRFGI"