Created
January 7, 2024 13:34
-
-
Save Phryxia/35f87532625600d447b83a7000a8dce2 to your computer and use it in GitHub Desktop.
TypeScript implementation of permutation of given elements with specific length.
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* permutate<T>(domain: T[], length: number) { | |
| function* recurse(stack: T[] = [], depth: number = 0): Generator<T[]> { | |
| if (depth >= length) { | |
| yield stack.slice() | |
| return | |
| } | |
| for (const element of domain) { | |
| stack[depth] = element | |
| yield* recurse(stack, depth + 1) | |
| } | |
| } | |
| yield* recurse() | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
It generates total 2^n unique (unless
domainhas duplicated elements) withdomainof lengthn.Mutability
Note that this never clone given elements in
domain. If you're handling mutable elements, change line 4 as followings: