Skip to content

Instantly share code, notes, and snippets.

@deng232
Last active April 22, 2024 03:27
Show Gist options
  • Save deng232/7efe6b6ed09670579bec3f3d1d6b32dd to your computer and use it in GitHub Desktop.
Save deng232/7efe6b6ed09670579bec3f3d1d6b32dd to your computer and use it in GitHub Desktop.
ts/js short Heap's algorithm for strings permutation
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