Search code examples
javascriptnode.jsalgorithmgoogle-chromeecmascript-2016

JavaScript - Sequence of letters


I want to create the function which should return n-th string from the sequence

a, b, c, ... , z, aa, ab, ... , az, ba, ... , zz, aaa, ...

for given number n (indexes start from zero).

This is the current my function:

const charCode = 'a'.charCodeAt(0);

function identName(a){
  var b = '';

  while(a){
    b = String.fromCharCode(charCode + a % 26) + b;
    a = a / 26 | 0;
  }

  return b || 'a';
}

There are 26 letters, so I divide by 26 and each time I concatenate char code of remainder (modulo 26) to the string b. However this is the output:

a b c d e f g h i j k l m n o p q r s t u v w x y z ba bb bc bd be ...

As you can see, two letter strings starts from ba. I tried to decrease by 1 in each iteration, but then the result is like this:

a a b c d e f g h i j k l m n o p q r s t u v w x y a' aa ab ac ad ...

There are string a two times and there is no z. What am I doing wrong? How to properly generate this sequence in optimal and fast way?

Edit

I really don't see what is unclear in my question. I simply want a function which is called like this identName(0) and returns "a", when called like this identName(1) returns "b", etc..., when called like this: identName(26) returns "aa" and so on. How can it be described simplier. I really don't udnerstand what is unclear here... :/


Solution

  • This should do the trick.

    const charCode = 'a'.charCodeAt(0);
    
    var identName = function (a) {
      var b = [a], sp, out, i, div;
    
        sp = 0;
        while(sp < b.length) {
            if (b[sp] > 25) {
                div = Math.floor(b[sp] / 26);
                b[sp + 1] = div - 1;
                b[sp] %= 26;
            }
            sp += 1;
        }
    
        out = "";
        for (i = 0; i < b.length; i += 1) {
            out = String.fromCharCode(charCode + b[i]) + out;
        }
    
        return out;
    }
    

    Essentially you were skipping over the 0 positions each time you got to the transition for example 27 -> 0,0 rather than 1,0.