javascriptheaps-algorithm

Different outputs for the same function with different callbacks (Heap's Algorithm)


I'm using the Heap's Algorithm and it's working well with the callback function output console logging the outcomes. But if I change the action of the callback function output to array.push, it pushes the same array over and over. What am I doing wrong?

let swap = function (array, index1, index2) {
    var temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;

    return array;
  };

  let permutationHeap = function (array, callback, n) {
    n = n || array.length;
    if (n === 1) {
      callback(array);
    } else {
      for (var i = 1; i <= n; i++) {
        permutationHeap(array, callback, n - 1);
        if (n % 2) {
          swap(array, 0, n - 1);
        } else {
          swap(array, i - 1, n - 1);
        }
      }
    }
  };

  let finalResult = [];

  var output = function (input) {
    //console.log(input);
    finalResult.push(input);
  };

  permutationHeap(["Mary", "John", "Denis"], output);
  
  console.log(finalResult)


Solution

  • An array is an Object, objects are pointers/references.. I used the spread operator to kinda clone the input so it doesnt keep doing the reference jitsu

    let swap = function (array, index1, index2) {
        var temp = array[index1];
        array[index1] = array[index2];
        array[index2] = temp;
    
        return array;
      };
    
      let permutationHeap = function (array, callback, n) {
        n = n || array.length;
        if (n === 1) {
          callback(array);
        } else {
          for (var i = 1; i <= n; i++) {
            permutationHeap(array, callback, n - 1);
            if (n % 2) {
              swap(array, 0, n - 1);
            } else {
              swap(array, i - 1, n - 1);
            }
          }
        }
      };
    
      let finalResult = [];
    
      var output = function (input) {
        //console.log(input);
        finalResult.push([...input]); //spread operator >:D
      };
    
      permutationHeap(["Mary", "John", "Denis"], output);
      
      console.log(finalResult)