在具有重复项的所有可能排列的列表中查找给定字符串的等级

时间:2013-07-12 17:30:27

标签: javascript algorithm ranking

我试图在排列列表中找到给定字符串的排名,并希望有人能找到该错误。

function permute() {
    var W = $('input').val(),
        C = [];
    for (var i = 0; i < 26; i++) C[i] = 0;
    var rank = 1;
    for (var i = 0; i < W.length; i++) {
        C[W.charCodeAt(i) - 'a'.charCodeAt(0)]++;
    }
    var repeated= 1;
    for (var i = 0; i < C.length; i++) {
        if(C[i] > 0) {
            repeated *=  fact(C[i]);
        }
    }    

    if (W !== '') {
        for (var i = 0; i < W.length; i++) {
            //How many characters which are not used, that come before current character
            var count = 0;
            for (var j = 0; j < 26; j++) {
                if (j == (W.charCodeAt(i) - 'a'.charCodeAt(0))) break;
                if (C[j] > 0) count++;
            }
            C[W.charCodeAt(i) - 'a'.charCodeAt(0)] = 0;
            rank += ( count * fact(W.length - i - 1) );
        }
        rank = rank/ repeated;
    }
    var pp = 'Rank of  :: ' + W + ' -- ' + rank;
    $('div').append('<p>' + pp + '</p>');
}

function fact(n) {
    if (n == 0 || n == 1) return 1;
    else return fact(n - 1) * n;
}

$('button').click(permute);

Check Fiddle

用例可能是

bookkeeper的排名应该是 10743

1 个答案:

答案 0 :(得分:2)

这是demo

对于每个位置,检查剩下多少个字符有重复,并使用逻辑,如果你需要置换n个东西,如果'a'的东西是相似的,排列的数量是n!/a!