本文介绍了查找给定字符串的排名与重复所有可能的排列名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到排列的列表中指定字符串的排名,并希望有人能找到的bug。
I was trying to find the Rank of the given string in the list of permutations and was hoping someone can find the bug.
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
一个用例,这可能是
会计
是应该给的等级 10743
推荐答案
这里是演示:
对于每个位置上检查有多少留字有重复的,使用的逻辑,如果你需要重排ñ东西,如果'一'的东西是相似的排列数为 N!/年!
For each position check how many characters left have duplicates, and use the logic that if you need to permute n things and if 'a' things are similar the number of permutations is n!/a!
这篇关于查找给定字符串的排名与重复所有可能的排列名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!