Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Created January 7, 2024 13:34
Show Gist options
  • Save Phryxia/35f87532625600d447b83a7000a8dce2 to your computer and use it in GitHub Desktop.
Save Phryxia/35f87532625600d447b83a7000a8dce2 to your computer and use it in GitHub Desktop.
TypeScript implementation of permutation of given elements with specific length.
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()
}
@Phryxia
Copy link
Author

Phryxia commented Jan 7, 2024

Example

It generates total 2^n unique (unless domain has duplicated elements) with domain of length n.

  • Generation order is lexiographic.
  • Every generated arrays are independent objects
console.log([...permutate([0, 1], 3)])

// log followings
// [
//   [0, 0, 0],
//   [0, 0, 1],
//   [0, 1, 0],
//   [0, 1, 1],
//   [1, 0, 0],
//   [1, 0, 1],
//   [1, 1, 0],
//   [1, 1, 1],
// ]

Mutability

Note that this never clone given elements in domain. If you're handling mutable elements, change line 4 as followings:

yield stack.map(element => element.clone())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment