Search for the rank of a given string in the list of all possible permutations using Duplicates

I tried to find the rank of a given line in the permutation list and was hoping that someone would find an error.

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 feed

Use case for this might be

bookkeepermust give a rank of 10743 .

+1
source share
1 answer

Here's a demo :

For each position, check how many remaining characters have duplicates, and use logic that, if you need to rearrange n things, and if "a" looks like the number of permutations n!/a!

+2
source

Source: https://habr.com/ru/post/1533381/


All Articles