MCPcopy Create free account
hub / github.com/cortex-js/compute-engine / permutations

Function permutations

src/common/utils.ts:29–70  ·  view source on GitHub ↗
(
  xs: ReadonlyArray<T>,
  condition?: (
    xs: ReadonlyArray<T> /* , generated: Set<Y> | Set<[Y,T]>? */
  ) => boolean
  // cacheKey?: (T) => Y
)

Source from the content-addressed store, hash-verified

27 * @returns
28 */
29export function permutations<T /* , Y extends any = any */>(
30 xs: ReadonlyArray<T>,
31 condition?: (
32 xs: ReadonlyArray<T> /* , generated: Set<Y> | Set<[Y,T]>? */
33 ) => boolean
34 // cacheKey?: (T) => Y
35): ReadonlyArray<ReadonlyArray<T>> {
36 // Guard against combinatorial explosion: n! grows very fast
37 // 7! = 5040, 8! = 40320, 9! = 362880, 10! = 3628800
38 if (xs.length > MAX_PERMUTATION_ELEMENTS) {
39 console.assert(
40 false,
41 `permutations(): input has ${xs.length} elements, which exceeds the limit of ${MAX_PERMUTATION_ELEMENTS}. ` +
42 `This would generate ${factorial(
43 xs.length
44 )} permutations. Returning empty array to prevent memory exhaustion.`
45 );
46 return [];
47 }
48
49 const result: ReadonlyArray<T>[] = [];
50
51 const permute = (arr: T[], m: T[] = []) => {
52 if (arr.length === 0) {
53 if (!condition || condition(m)) {
54 // Use spread operator to create a shallow copy of m
55 result.push([...m]);
56 }
57 } else {
58 for (let i = 0; i < arr.length; i++) {
59 const curr = arr.slice();
60 const next = curr.splice(i, 1);
61 permute(curr.slice(), m.concat(next));
62 }
63 }
64 };
65
66 //@fix: (typing)
67 permute(xs as T[]);
68
69 return result;
70}
71
72/** Helper to compute factorial for error messages */
73function factorial(n: number): number {

Callers 1

matchPermutationFunction · 0.90

Calls 3

assertMethod · 0.80
factorialFunction · 0.70
permuteFunction · 0.70

Tested by

no test coverage detected