Created
February 14, 2013 23:02
-
-
Save cutthroat/4957198 to your computer and use it in GitHub Desktop.
Heap's method for generating permutations
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
// Heap's method, see Sedgewick (1977) | |
function eachPerm(a, callback, target) { | |
var n = a.length; | |
var c = new Array(n); | |
var j = n; | |
while (j--) { c[j] = 0; } | |
var m = 0; | |
callback.call(target, a, m++); | |
var i = 1; | |
do { | |
if (c[i] < i) { | |
j = (i % 2 ? c[i] : 0); | |
var x = a[j]; a[j] = a[i]; a[i] = x; | |
++c[i]; i = 1; | |
callback.call(target, a, m++); | |
} | |
else { | |
c[i++] = 0; | |
} | |
} while (i < n); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment