Created
November 10, 2017 12:21
-
-
Save asartalo/aab32aeb7daf285ca731217355a6612e to your computer and use it in GitHub Desktop.
Algorithm: Heap Permutation
This file contains hidden or 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
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