Last active
May 15, 2018 22:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@danieldrasdo: Fixed the typo, thanks! Glad it helped you. 😄