如何在 JS 中创建数组的排列但具有给定数量的字符

How to create permutation of array in JS but with the given amount of chars

我有一个包含一些字符的数组:


    var ar1 = ["a", "1"];

我想用这个数组的所有排列创建数组,但是它会像这样给定数量的插槽:

如果插槽数量为 3,则数组将如下所示:

    ["a", "1", "a"]
    ["1", "a", "1"]
    ["a", "a", "a"]
    ["1", "1", "1"]
    ["a", "a", "1"]
    ["1", "1", "a"]
    ["a", "1", "1"]
    ["1", "a", "a"]

等等...

我怎样才能做到这一点?

我会用递归来解决这个问题,就像这样:

function permutations(possibleCharacters, n){
    const result = [];

    if(n == 0){
        return [[]];
    }

    const subProblemResult = permutations(possibleCharacters, n - 1);

    for(let character of possibleCharacters){
        for(let sub of subProblemResult){
            result.push([character].concat(sub));
        }
    }

    return result;
}

console.log(permutations(["a", "1"], 3));

我建议滥用 toString() 方法:

var ar1 = ["a", "1"]

let n = 3
let base = ar1.length

let output = []

for(let i = 0; i < base**n; ++i) {
  output.push(i
    .toString(base)
    .padStart(n, '0')
    .split('')
    .map(x => ar1[parseInt(x, base)])
  )
}

console.log(output)

这样可以避免递归。

问题:在给定每个组合的值和长度的情况下,找到输入的所有可能组合。 inp = Input(Array), Len = 每个组合的长度。

function permutation(inp, len) {
   let posComb = 1,  r = 1;
   for ( let i =1; i<n/2+1; i++ )  {
      posComb = posComb * (inp-i+1)
      r = r * i;
      if ( posComb / r == inp ) return i;      
   }
   return -1;
} 

解释:这会找到所有可能的 a 和输入组合以及所需的长度。现在你只需要创建一个数组并用排列填充它,现在你确切地知道有多少了。

感谢来自 CodeWar for Code 的 dcislak。