Heap's Algorithm

In this example below you will see how to do a Heap's Algorithm with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by DanRom624, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright DanRom624 ©
  • HTML
  • CSS
  • JavaScript
    

/*Downloaded from https://www.codeseek.co/DanRom624/heapandaposs-algorithm-vGwGmW */
    


/*Downloaded from https://www.codeseek.co/DanRom624/heapandaposs-algorithm-vGwGmW */
    var swap = function(array, pos1, pos2) {
  var temp = array[pos1];
  array[pos1] = array[pos2];
  array[pos2] = temp;
};

var heapPerm = function(array, output, n) {
  n = n || array.length;
  if (n === 1) {
    output(array);
  } else {
    for (var i = 1; i <= n; i += 1) {
      heapPerm(array, output, n - 1);
      if (n % 2) {
        var j = 1;
      } else {
        var j = i;
      }
      swap(array, j - 1, n - 1);
    }
  }
};

var newArray = [];
heapPerm([1,2,3,4], function(pippo) {
  //console.log("input", pippo);
  var tempStr = pippo.join('');
  //console.log("tempStr", tempStr);
  //console.log("newArray", newArray);
  newArray.push(tempStr);
});
console.log("Finale", newArray.sort());

/*
var swap = function(array, pos1, pos2) {
  var temp = array[pos1];
  array[pos1] = array[pos2];
  array[pos2] = temp;
};

function heapPerm(array, pallino, n) {

  
  console.log("+++++++");
  console.log("array", array);
  console.log("output", pallino);
 
  console.log("n", n);
 
 console.log("array.length", array.length);


  n = n || array.length; // set n default to array.length
  if (n === 1) {
    console.log("sono qui!", array);
    console.log("Old-newArray", newArray);
    //newArray = Array.push.apply(newArray, array);
    Array.prototype.push.apply(newArray, array);
    console.log("New-newArray", newArray);

  } else {
    for (var i = 1; i <= n; i += 1) {
      heapPerm(array, pallino, n - 1);
      if (n % 2) {
        var j = 1;
      } else {
        var j = i;
      }
      swap(array, j - 1, n - 1); // -1 to account for javascript zero-indexing
    }
  }
};

var newArray = [];
heapPerm(['a', 'b', 'c'], function(pippo) {
  //console.log("-------");
  console.log("input", pippo);
  //console.log("newArray", newArray);
  //newArray = newArray.push(input);
});
//console.log(newArray);



function heapPerm (array, output) {
  array.join('');
  return array;
}

heapPerm(['a', 'b', 'c'], function(pippo) {
  //console.log("-------");
  console.log("input", pippo);
});

*/

Comments