Last active
April 22, 2024 03:27
-
-
Save deng232/7efe6b6ed09670579bec3f3d1d6b32dd to your computer and use it in GitHub Desktop.
ts/js short Heap's algorithm for strings permutation
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 permutations = (combo: string[]): string[][] => { | |
// combo[] | |
return combo | |
.map((v, i, combo) => { | |
const right = [...combo] | |
const left = right.splice(i, 1)[0] // remove and return index from array; | |
if (right.length === 0) { | |
return [[left]] | |
} | |
return permutations(right).map((right) => [left, ...right]) | |
}) | |
.reduce((p: string[][], c) => p.concat(c)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment