Search code examples
javascriptsequencesequential

Sequential strings javascript


I'm stuck on sequential string generation, the last iteration of the code below, is trying to return ac.

var charcode = 'abcdefghijklmnopqrstuvwxyz0123456789_';
var arr = [];
var len = 1;
var current = 0;

for(var i = 0; i < 40; i++) {
    if(current == charcode.length) {
        current = 0
        len++
    }
    var tmpStr = ''
    for(var l = 0; l < len; l++) {
        tmpStr = tmpStr + charcode[current];
    }
    console.log(tmpStr)
    current++
}

However, it produces cc.

Sorry, somehow deleted the intended output

a, b, c ... aa, ab, ac ... ba, bc, bb ... ∞

My current understanding suggests within the l < len loop I should check if len > 1 and if so break out and loop for the current charcode[x] but I just can't wrap my head around breaking in and out as it grows.


Solution

  • You can do it like this:

    var charcode = 'abcdefghijklmnopqrstuvwxyz0123456789_';
    var arr = [];
    var len = 0;
    var current = 0;
    
    for(var i = 0; i < 40; i++) {
      if(current == charcode.length) {
         current = 0;
         len++;
      }
    
      var tmpStr = (len===0) ? '' : charcode[len-1];
    
      tmpStr = tmpStr + charcode[current];
      current++;
      console.log(tmpStr);
    }
    

    In brief, you didn't need a second loop, but an iteration instead (which is achieved through charcode[len-1]).

    JS Bin here.

    UPDATE

    If you need a continuos loop until the very end of the charset, you can use this:

    This one introduces a third variable (digits) to the iteration and choses a .substr() instead of a single character out of the charset, so that everytime the end of the charset is reached, another digit will be added. The variable called x sets the limit. I have tried 4000 and it looks like it is working.

    var charcode = 'abcdefghijklmnopqrstuvwxyz0123456789_',
        arr = [],
        len = 0,
        digits = 2,
        current = 0,
        tmpStr = '';
    
    var x = 4000;
    
    for(var i=0; i<x; i++) {
        if(current === charcode.length) {
            current = 0;
            len++;
            if(tmpStr.substr(0,1) === charcode.substr(-digits,1) || tmpStr === charcode.substr(-1) + '' + charcode.substr(-1)) {
                len = 1;
                digits++;
            }  
         }
    
         if(digits === charcode.length) {
             console.log(charcode);
             console.log(i + ' results found');
             break;
         }
    
         tmpStr = (len===0) ? '' : charcode.substr([len-1], digits-1);
    
         tmpStr += charcode[current];
         current++;
         console.log(tmpStr);
    }
    

    Final JS Bin here.