如何在JavaScript中使用给定数量的元素创建数组的排列

我们需要编写一个JavaScript函数,该函数以文字数组作为第一个参数,并以数字作为第二个参数。

该函数应构造一个包含所有此类数组的数组,这些数组的长度等于第二个参数指定的数字,并包含输入数组元素的所有可能排列。

例如-

如果输入数组和数字为-

const arr = ['k', 5];
const num = 3;

那么输出应该是-

const output = [
   [ 'k', 'k', 'k' ],
   [ 'k', 'k', 5 ],
   [ 'k', 5, 'k' ],
   [ 'k', 5, 5 ],
   [ 5, 'k', 'k' ],
   [ 5, 'k', 5 ],
   [ 5, 5, 'k' ],
   [ 5, 5, 5 ]
];

示例

以下是代码-

const arr = ['k', 5];
const num = 3;
const allPairs = (arr = [], num) => {
   const res = [];
   if(num === 0){
      return [[]];
   }
   const subResult = allPairs(arr, num - 1);
   for(let el of arr){
      for(let sub of subResult){
         res.push([el].concat(sub));
      }
   }
   return res;
}
console.log(allPairs(arr, num));
输出结果

以下是控制台输出-

[
   [ 'k', 'k', 'k' ],
   [ 'k', 'k', 5 ],
   [ 'k', 5, 'k' ],
   [ 'k', 5, 5 ],
   [ 5, 'k', 'k' ],
   [ 5, 'k', 5 ],
   [ 5, 5, 'k' ],
   [ 5, 5, 5 ]
]

猜你喜欢