Increment a string with letters?

前端 未结 12 1275
礼貌的吻别
礼貌的吻别 2021-02-08 12:35

I need to increment a string from.. let\'s say aaa to zzz and write every incrementation in the console (is incrementation even a word?). It would go s

相关标签:
12条回答
  • 2021-02-08 12:53

    Took a bit of algorithmic approach. This function takes initial string as an argument, increments next possible char in alphabet and at last returns the result.

    function generate(str)
    {
      var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
      var chars = [];
      for(var i = 0; i < str.length; i++)
      {
        chars.push(alphabet.indexOf(str[i]));
      }
      for(var i = chars.length - 1; i >= 0 ; i--)
      {
        var tmp = chars[i];
        if(tmp >= 0 && tmp < 25) {
          chars[i]++;
          break;
        }
        else{chars[i] = 0;}
      }
      var newstr = '';
      for(var i = 0; i < chars.length; i++)
      {
        newstr += alphabet[chars[i]];
      }
      return newstr;
    } 
    

    Here is the loop helper function which accepts the initial string to loop through and generate all combinations.

    function loop(init){
      var temp = init;
      document.write(init + "<br>");
      while(true)
      {
        temp = generate(temp);
        if(temp == init) break;
        document.write(temp + "<br>");
      }
    }
    

    Usage: loop("aaa");

    CODEPEN

    0 讨论(0)
  • 2021-02-08 12:56

    Interesting approach with Number#toString:

    var n = 13330
    var ns = []
    
    for(var i = 0; i < 26; i++) {
      for(var j = 0; j < 26; j++) {
        for(var k = 0; k < 26; k++) {
          ns.push(n.toString(36))
          n++
        }
        n += 10 // jump from '(x)0' to '(x+1)a', etc.
      }
      n += 360 // jump from '(x)0a' to '(x)aa', etc.
    }
    
    console.log(ns) // the strings you wanted
    
    0 讨论(0)
  • 2021-02-08 13:05

    Treat the string like it's a base 36 number.

    Convert it to decimal, add 1, convert back to base 36, and replace any zeroes with the letter 'a':

    var str= 'aaa',
        s= str;
    
    while(str!=='zzz') {
      str= ((parseInt(str, 36)+1).toString(36)).replace(/0/g,'a');
      s+= ' '+str;
    }
    
    document.body.innerHTML= s;

    0 讨论(0)
  • 2021-02-08 13:07

    The example below can work from a...a to z...z.

    String.prototype.replaceAt = function(index, character) {
      return this.substr(0, index) + character + this.substr(index + character.length);
    }
    
    String.prototype.inc = function() {
      var stop = 'z';
      var start = 'a';
      var currentIndex = this.length - 1;
      var string = this.replaceAt(currentIndex, String.fromCharCode(this.charCodeAt(currentIndex) + 1));
    
      for (var i = string.length - 1; i > 0; i--) {
        if (string[i] == String.fromCharCode(stop.charCodeAt(0) + 1)) {
          string = string.replaceAt(i - 1, String.fromCharCode(string.charCodeAt(i - 1) + 1));
          string = string.replaceAt(i, String.fromCharCode(start.charCodeAt(0)));
        }
      }
      return string;
    }
    
    var string = "aaa";
    var allStrings = string;
    while(string != "zzz") {
      string = string.inc();
      allStrings += " " + string;
    }
    document.getElementById("current").innerHTML = allStrings;
    <div id="current"></div>

    0 讨论(0)
  • 2021-02-08 13:08

    This will function will do the part of incrementing the string to next sequence

    function increment(str){
    
        var arr = str.split("");
        var c;
        for(var i=arr.length-1; i>=0; i--){
            c = (arr[i].charCodeAt(0)+1)%123;
            arr[i] = String.fromCharCode(c==0?97:c);
            if(c!=0)break;
        }
    return arr.join("");
    }
    

    I was working on another solution to increment by any number and also in reverse direction. The code still has some bugs, but just putting it up here to receive some suggestions. pass in negative numbers to go in reverse direction. Code fails for some edge cases, for eg: when character is 'a' and num is negative number

    function jumpTo(str,num){
    
        var arr = str.split("");
        var c;
        for(var i=arr.length-1; i>=0; i--){
            c = (arr[i].charCodeAt(0)+1)%123;
            c += c==0?97+num-1:num-1;
            arr[i] = String.fromCharCode(c==0?97:c);
            if(c!=0)break;
        }
    return arr.join("");
    }
    
    0 讨论(0)
  • 2021-02-08 13:10

    Gets A-Z, AA-ZZ, AAA-ZZZ etc. until the number of cycles is up.

    function createList(maxCycles) {
      if (typeof maxCycles != "number") {
        console.log("number expected");
        return;
      }
    
      const alphaLen = 26;
      const alpha = ["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"];
    
      let list = [alpha];
    
      // go through all cycles
      for (let cycleNo = 1; cycleNo < maxCycles; cycleNo++) {
        list[cycleNo] = [];
        pastCollection = list[cycleNo - 1];
        pastLen = pastCollection.length;
    
        for (let i = 0; i < pastLen; i++) {
          for (let j = 0; j < alphaLen; j++) {
            // use past item then add a letter of the alphabet at the end
            list[cycleNo].push(pastCollection[i] + alpha[j]);
          }
        }
      }
    
      return list;
    }
    
    (function(maxCycles) {
      console.log(createList(maxCycles));
    })(3);

    0 讨论(0)
提交回复
热议问题