Skip to content

Instantly share code, notes, and snippets.

@dsernst
Last active May 15, 2018 22:53
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dsernst/2570de0dc7d44a8cbbd0 to your computer and use it in GitHub Desktop.
Save dsernst/2570de0dc7d44a8cbbd0 to your computer and use it in GitHub Desktop.
A JavaScript implement of Heap's efficient Permutation Algorithm: https://en.wikipedia.org/wiki/Heap%27s_algorithm
var swap = function (array, pos1, pos2) {
var temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
};
var heapsPermute = function (array, output, n) {
n = n || array.length; // set n default to array.length
if (n === 1) {
output(array);
} else {
for (var i = 1; i <= n; i += 1) {
heapsPermute(array, output, 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
}
}
};
// For testing:
var print = function(input){
console.log(input);
}
heapsPermute(['a', 'b', 'c', 'd'], print);
// heapsPermute([1, 2, 3], print)
@dsernst
Copy link
Author

dsernst commented Jan 4, 2015

@danieldrasdo
Copy link

Thank you so much for this!
A quick spelling error I found, in the console.log on line 27, should be input, not intput.

Thanks again!

@dsernst
Copy link
Author

dsernst commented Oct 4, 2016

@danieldrasdo: Fixed the typo, thanks! Glad it helped you. 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment