Created
November 29, 2018 14:30
-
-
Save bobwei/ed3144fa5288c2b96a3fda29f9e5c840 to your computer and use it in GitHub Desktop.
permutation.js
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
const createPermutation = (arr, selected = new Set(), output = []) => { | |
if (selected.size >= arr.length) { | |
output.push([...selected].map((i) => arr[i])); | |
return output; | |
} | |
for (let i = 0; i < arr.length; i++) { | |
if (selected.has(i)) { | |
continue; | |
} | |
selected.add(i); | |
createPermutation(arr, selected, output); | |
selected.delete(i); | |
} | |
return output; | |
}; | |
const result = createPermutation([1, 2, 3]); | |
console.log(result); | |
/* | |
[ | |
[ 1, 2, 3 ], | |
[ 1, 3, 2 ], | |
[ 2, 1, 3 ], | |
[ 2, 3, 1 ], | |
[ 3, 1, 2 ], | |
[ 3, 2, 1 ] | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment