Skip to content

Instantly share code, notes, and snippets.

@asartalo
Created November 10, 2017 12:21
Show Gist options
  • Save asartalo/aab32aeb7daf285ca731217355a6612e to your computer and use it in GitHub Desktop.
Save asartalo/aab32aeb7daf285ca731217355a6612e to your computer and use it in GitHub Desktop.
Algorithm: Heap Permutation
function permute(arr) {
const permutations = [];
function heapPerm(array, size) {
if (size === 1) {
permutations.push(array.slice(0));
}
for (let i = 0; i < size; i++) {
const prev = size - 1;
heapPerm(array, prev);
if (size % 2 === 0) {
[ array[0], array[prev] ] = [ array[prev], array[0] ]
} else {
[ array[i], array[prev] ] = [ array[prev], array[i] ]
}
}
}
heapPerm(arr, arr.length);
return permutations;
}
/*
console.log(permute([1, 2, 3]));
[
[1, 2, 3],
[2, 1, 3],
[3, 2, 1],
[2, 3, 1],
[3, 1, 2],
[1, 3, 2]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment