Home > Mobile >  How do array permutation splitting by (n)
How do array permutation splitting by (n)

Time:05-04

So I have array

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

I want to get all possible combinations of this array splitted by (n) number for example

function getNPermutate(arr, n) {
 
}

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

!array can be any length

I found the solution with simple permutation, but dont understand how do splitted permutation

 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]))

CodePudding user response:

You can try this one:

Script:

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;
}

Output:

output

CodePudding user response:

You could use a recursive generator:

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);

To convert the generator to a normal function that returns a nested array, do:

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