数组排列如何拆分(n)

How do array permutation splitting by (n)

所以我有数组

const arr = [ 1, 4, 5, 8]

我想得到这个数组所有可能的组合,除以 (n) 个数 例如

function getNPermutate(arr, n) {
 
}

getNPermutate(arr, 3) // [[1, 4, 5], [1, 4, 8], [4, 5, 8],[1, 5 ,8] ]

!array 可以是任意长度

我找到了简单排列的解决方案,但不明白如何拆分排列

 function permute(nums) {
  let result = [];
  if (nums.length === 0) return [];
  if (nums.length === 1) return [nums];
  for (let i = 0; i < nums.length; i++) {
    const currentNum = nums[i];
    const remainingNums = nums.slice(0, i).concat(nums.slice(i + 1));
    const remainingNumsPermuted = permute(remainingNums);
   for (let j = 0; j < remainingNumsPermuted.length; j++) {
      const permutedArray =  [currentNum].concat(remainingNumsPermuted[j]);
      result.push(permutedArray);
    }
  }
  return result;
}

console.log(permute([1,2,3,4]))

你可以试试这个:

脚本:

function test() {
  var array = [1, 4, 5, 8];

  console.log(getCombinations(array, 3)) 
}

function getCombinations(chars, len) {
  var result = [];
  var f = function(prefix, chars) {
    for (var i = 0; i < chars.length; i++) {
      var elem = [...prefix, chars[i]];
      if(elem.length == len)
        result.push(elem);
      f(elem, chars.slice(i + 1));
    }
  }
  f([], chars);
  return result;
}

输出:

您可以使用递归生成器:

function* iterPerms(arr, n, first=0) {
    if (n > arr.length - first) return;
    if (n === 0) return yield [];
    for (const res of iterPerms(arr, n - 1, first + 1)) yield [arr[first], ...res];
    yield* iterPerms(arr, n, first + 1);
}

const arr = [1, 4, 5, 8];
for (let perm of iterPerms(arr, 3)) console.log(...perm);

要将生成器转换为 returns 嵌套数组的普通函数,请执行:

const getNPermutate = (arr, n) => Array.from(iterPerms(arr, n));