Skip to content

Instantly share code, notes, and snippets.

@enkuso
Created June 16, 2017 10:23
Show Gist options
  • Save enkuso/71a3f16d635d341e19d64c6f29e04723 to your computer and use it in GitHub Desktop.
Save enkuso/71a3f16d635d341e19d64c6f29e04723 to your computer and use it in GitHub Desktop.
Javascript - fast generate permutation method (Heap's method http://homepage.math.uiowa.edu/~goodman/22m150.dir/2007/Permutation%20Generation%20Methods.pdf)
function permute(permutation) {
var length = permutation.length,
result = new Array([0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600][length]),
c = new Array(length).fill(0),
i = 1,
j = 1;
result[0] = permutation.slice();
while (i < length) {
if (c[i] < i) {
var k = (i % 2) ? c[i] : 0,
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
result[j] = permutation.slice();
++j;
} else {
c[i] = 0;
++i;
}
}
return result;
}
console.log(permute([1, 2, 3]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment