如何找到一个给定的字符串,其职级排列?职级、字符串、排列

2023-09-11 00:12:55 作者:゛浮夸的外表

例如,

rank  permutation   
0     abc
1     acb
2     bac
3     bca
4     cab
5     cba

所以,如果有人问,给我的频带排列秩为4,答案是驾驶室。请给Java的code对这一计划

So, if one asks give me permutation with rank 4, the answer is cab. Pls give the java code for this program

推荐答案

我在第一次尝试做它! :-) 真的好功课,漂亮的问题,你让我很快乐!这是在JavaScript的解决方案:

I made it at a first attempt!! :-) Really good homework, nice problem, you made my day! Here is a solution in javascript:

function permutation (rank, n, chars) 
{
    var fact, char_idx, this_char;

    if (n == 0)
        return "";

    char_idx = Math.floor(rank / factorial(n - 1));

    this_char = chars.splice(char_idx, 1); 
         // returns the char with index char_idx and removes it from array

    return this_char + 
        permutation(rank % factorial(n - 1), n - 1, chars);
}

只是把它像置换(5,3,['A','B','C']),就是这样。 你必须写自己的阶乘()函数 - 作为一个家庭作业: - )

Just call it like permutation(5, 3, ['a', 'b', 'c']) and that's it. You have to write your own factorial() function - as a homework :-)