我怎么可能缩短这个脚本而不是我这样做呢?

时间:2014-02-21 16:57:21

标签: javascript arrays for-loop

尝试遍历每个可能的字符组合。我试过混合各种数组,需要大约三行,但后来我无法连接。或者也许还有更好的连接方式?我在引号之间的+'+字母应该是一个换行符但stackoverflow不允许:P对不起如果我太模糊了我只是缩短了这个脚本并改变了它的工作方式相同但是stackoverflow允许?

function go() {
        var letters = ('abcdefghijklmnopqrstuvwxyz').split('');
        var p1 = '';
        var p2 = '';
        for (var i = 0;i < 27; i++) {
            var p1 = p1+''+letters[i];
            var p2 = p2+''+letters[0]+letters[i];
            var p3 = p3+''+letters[1]+letters[i];
            var p4 = p4+''+letters[2]+letters[i];
            var p5 = p5+''+letters[3]+letters[i];
            var p6 = p6+''+letters[4]+letters[i];
            var p7 = p7+''+letters[5]+letters[i];
            var p8 = p8+''+letters[6]+letters[i];
            var p9 = p9+''+letters[7]+letters[i];
            var p10 = p10+''+letters[8]+letters[i];
            var p11 = p11+''+letters[9]+letters[i];
            var p12 = p12+''+letters[10]+letters[i];
            var p13 = p13+''+letters[11]+letters[i];
            var p14 = p14+''+letters[12]+letters[i];
            var p15 = p15+''+letters[13]+letters[i];
            var p16 = p16+''+letters[14]+letters[i];
            var p17 = p17+''+letters[15]+letters[i];
            var p18 = p18+''+letters[16]+letters[i];
            var p19 = p19+''+letters[17]+letters[i];
            var p20 = p20+''+letters[18]+letters[i];
            var p21 = p21+''+letters[19]+letters[i];

        }
}

1 个答案:

答案 0 :(得分:0)

通常,为了创建字符组合,您可以使用这样的递归(或只是一个堆栈):

function handleString(str) {

    if (str is valid combination of characters by Your rules) {

        doSomething(str);
    }

    for each character c that may be added to incomplete str by Your rules {

        handleString(str + c);
    }
}

你必须小心不要创建无休止的递归,这一切都取决于你的规则。例如,要创建字母“abcdefgh”之外的所有可能的3个字符的字符串,它可能如下所示:

function handleString(str, alphabet, length) {

    // just in case...
    if (str.length > length)
        return;

    // if the string has desired length (my rule), use it as a valid combination
    if (str.length === length) {

        console.log(str);
        return;
    }

    // string doesn't have desired length yet, try adding 
    // each one of possible characters from the alphabet (my rule)
    for (var i = 0; i < alphabet.length; i++)
        handleString(str + alphabet.charAt(i), alphabet, length);
}

handleString("", "abcdefgh", 3);