Search code examples
javascriptalgorithmpermutation

How do array permutation splitting by (n)


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

Solution

  • 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