Increment a string with letters?

前端 未结 12 1281
礼貌的吻别
礼貌的吻别 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 13:15

    This function gives 3 characters based on a number:

    function n2s (n) {
        var s = '';
        while (s.length < 3) {
            s = String.fromCharCode(97 + n % 26) + s;
            n = Math.floor(n / 26);
        }
        return s;
    }
    

    To print strings from "aaa" to "zzz":

    var zzz = Math.pow(26, 3) - 1;
    for (var n = 0; n <= zzz; n++) {
        console.log(n2s(n));
    }
    

    function n2s (n) {
        var s = '';
        while (s.length < 3) {
            s = String.fromCharCode(97 + n % 26) + s;
            n = Math.floor(n / 26);
        }
        return s;
    }
    
    var result = [];
    var zzz = Math.pow(26, 3) - 1;
    for (var n = 0; n <= zzz; n++) {
        result.push(n2s(n));
    }
    document.body.innerHTML = result.join(' ');

    Ask for details :-)


    Improvements

    Performances compared to the accepted answer: http://jsperf.com/10-to-26.

    // string to number: s2n("ba") -> 26
    function s2n(s) {
        var pow, n = 0, i = 0;
        while (i++ < s.length) {
            pow = Math.pow(26, s.length - i);
            n += (s.charCodeAt(i - 1) - 97) * pow;
        }
        return n;
    }
    
    // number to string: n2s(26) -> "ba"
    function n2s(n) {
        var s = '';
        if (!n) s = 'a'; 
        else while (n) {
            s = String.fromCharCode(97 + n % 26) + s;
            n = Math.floor(n / 26);
        }
        return s;
    }
    
    // pad("ba", 4) -> "aaba"
    function pad (s, n) {
        while (s.length < n) s = 'a' + s;
        return s;
    }
    

    Usage:

    var from = s2n('azx');
    var to = s2n('baa');
    for (var n = from; n <= to; n++) {
        console.log(pad(n2s(n), 3));
    }
    

    Output:

    azx
    azy
    azz
    baa
    

    Recursivity

    Probably less efficient in terms of memory use or computation time: https://jsperf.com/10-to-26/4.

    function n2s(n) {
        var next = Math.floor(n / 26);
        return (
            next ? n2s(next) : ''
        ) + (
            String.fromCharCode(97 + n % 26)
        );
    }
    
    function s2n(s) {
        return s.length && (
            (s.charCodeAt(0) - 97)
        ) * (
            Math.pow(26, s.length - 1)
        ) + (
            s2n(s.slice(1))
        );
    }
    

提交回复
热议问题