Search code examples
javascriptrecursionslicepermutationsplice

Didn't understand how the splice method works in the recursion call for permutation purpose


I get little trouble with an algorithm about permutation well I found it in full-stack overflow

 function permutator(inputArr) {
  var results = [];

  function permute(arr, memo) {
    var cur, memo = memo || [];

    for (var i = 0; i < arr.length; i++) {
      cur = arr.splice(i, 1);
      if (arr.length === 0) {
        results.push(memo.concat(cur));
      }
      permute(arr.slice(), memo.concat(cur));
      arr.splice(i, 0, cur[0]);(what's the purpose of this statement ????)
    }

    return results;
  }

  return permute(inputArr);
}

actually, I didn't understand how the recursion call work exactly I didn't understand how the splice method work in this recursion call I mean for example let's take an array of [0,1,2,3,4,5,6,7] in each iteration we run cur = arr.splice(i, 1) normally we get cur =0 then cur = 2, then 4 then 6 and so on ..., so when I log the memo and the arr variables in the console I got this enter image description here


Solution

  • Its a complex method to solve this type of problem, to understand this we need to simplify the problem,

    After some modification this code is much readable!

    function permutator(inputArr) {
        var results = [];
        function permute(arr, memo = []) {
            for (var i = 0; i < arr.length; i++) {
                let temp = [...arr], mem = memo.concat(temp.splice(i, 1));
                if (temp.length === 0) results.push(mem);
                permute(temp, mem);
            }
        }
        permute(inputArr);
        return results
    }
    console.log(permutator([1, 2, 3]))

    So basically in original code, they modify arr (only for short time) and later (in this line arr.splice(i, 0, cur[0]);) restore back to it's original state.

    splice method accept 3 arguments (start, deleteCount?, ...items?), And return an array containing the deleted elements. I recommend you to read more about Array.splice(),

    Example:

    let numbers = [1, 2, 3, 4, 5];
    console.log({ numbers })
    
    let deleted_elements = numbers.splice(0, 2);
    console.log('Removing first 2 elements from `numbers`', { deleted_elements, numbers })
    
    numbers.splice(0, 0, ...deleted_elements);
    console.log("Push `deleted_elements` in there original place", { numbers })