为什么我的字符串置换算法只能用3个或更少的字母?

时间:2013-06-16 03:19:35

标签: javascript algorithm permutation

守则:

function recursiveParse(letters, index) {
    var i,
        index = index || 0;
        stringOfLetters = '';

    while(index < letters.length) {
        stringOfLetters += letters[index] + recursiveParse(letters, ++index);
    }
    return stringOfLetters;
}

function calcPermutations(letters, index, permutations) {
    var head,
        index = index || 0,
        i,
        swapLetters,
        permutation,
        permutations = permutations || {};

    swapLetters = function(letters, index1, index2) {
        var tmp = letters[index2];

        letters[index2] = letters[index1];
        letters[index1] = tmp;

        return letters;
    }
    if(index < letters.length) {
        head = letters.splice(index, 1).join('');

        for(i = 0; i < letters.length; i++) {
            permutation = head + swapLetters(letters.slice(0), index, i).join('');
            permutations[permutation] = true;
        }
        letters.splice(index, 0, head);
        calcPermutations(letters, ++index, permutations); 
    }
    return permutations;
}

function testPermutations() {
    var expectedPermutations = ['atr', 'rat', 'rta', 'tar', 'tra', 'art'],
        actualPermutations = calcPermutations(['a', 'r', 't']);

    for(var i = 0; i < expectedPermutations.length - 1; i++) {
        if(actualPermutations[expectedPermutations[i]] !== true) {
            console.log("You're missing " + expectedPermutations[i]);
        } else {
            console.log("You've got " + expectedPermutations[i]);
        }
    }
    return actualPermutations;
}
testPermutations();

当我运行testPermutations并传入一个3个字母的单词时,它运行正常。然而,当我尝试四次时,一堆排列将会丢失。我的逻辑中有什么缺陷?

0 个答案:

没有答案