Skip to content

Instantly share code, notes, and snippets.

@aryelgois
Last active May 27, 2022 21:45
Show Gist options
  • Save aryelgois/ef63bfbd8cbb5fa8cdd8cde84855d37b to your computer and use it in GitHub Desktop.
Save aryelgois/ef63bfbd8cbb5fa8cdd8cde84855d37b to your computer and use it in GitHub Desktop.
Permute elements in array
export function* permute<T>(arr: T[], m: T[] = []): Generator<T[]> {
if (arr.length === 0) {
yield m
} else {
for (let i = 0; i < arr.length; i++) {
const curr = arr.slice()
const next = curr.splice(i, 1)
yield* permute(curr.slice(), m.concat(next))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment