@ac-kit/algo 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +44 -15
  3. package/dist/combinatorics/cartesian-product.d.ts +46 -0
  4. package/dist/combinatorics/cartesian-product.d.ts.map +1 -0
  5. package/dist/combinatorics/cartesian-product.js +79 -0
  6. package/dist/combinatorics/cartesian-product.js.map +1 -0
  7. package/dist/combinatorics/permutations.d.ts +41 -0
  8. package/dist/combinatorics/permutations.d.ts.map +1 -0
  9. package/dist/combinatorics/permutations.js +70 -0
  10. package/dist/combinatorics/permutations.js.map +1 -0
  11. package/dist/combinatorics/power-set.d.ts +40 -0
  12. package/dist/combinatorics/power-set.d.ts.map +1 -0
  13. package/dist/combinatorics/power-set.js +67 -0
  14. package/dist/combinatorics/power-set.js.map +1 -0
  15. package/dist/graph/bfs.d.ts +66 -0
  16. package/dist/graph/bfs.d.ts.map +1 -0
  17. package/dist/graph/bfs.js +89 -0
  18. package/dist/graph/bfs.js.map +1 -0
  19. package/dist/graph/connected-components.d.ts +35 -0
  20. package/dist/graph/connected-components.d.ts.map +1 -0
  21. package/dist/graph/connected-components.js +75 -0
  22. package/dist/graph/connected-components.js.map +1 -0
  23. package/dist/graph/floyd-warshall.d.ts +67 -0
  24. package/dist/graph/floyd-warshall.d.ts.map +1 -0
  25. package/dist/graph/floyd-warshall.js +106 -0
  26. package/dist/graph/floyd-warshall.js.map +1 -0
  27. package/dist/graph/graph-cycle-error.d.ts +16 -0
  28. package/dist/graph/graph-cycle-error.d.ts.map +1 -0
  29. package/dist/graph/graph-cycle-error.js +20 -0
  30. package/dist/graph/graph-cycle-error.js.map +1 -0
  31. package/dist/graph/lowest-common-ancestor.d.ts +32 -0
  32. package/dist/graph/lowest-common-ancestor.d.ts.map +1 -0
  33. package/dist/graph/lowest-common-ancestor.js +56 -0
  34. package/dist/graph/lowest-common-ancestor.js.map +1 -0
  35. package/dist/graph/topological-sort.d.ts +51 -0
  36. package/dist/graph/topological-sort.d.ts.map +1 -0
  37. package/dist/graph/topological-sort.js +124 -0
  38. package/dist/graph/topological-sort.js.map +1 -0
  39. package/dist/group/_nest-by.d.ts +19 -0
  40. package/dist/group/_nest-by.d.ts.map +1 -0
  41. package/dist/group/_nest-by.js +85 -0
  42. package/dist/group/_nest-by.js.map +1 -0
  43. package/dist/group/count-by.d.ts +31 -0
  44. package/dist/group/count-by.d.ts.map +1 -0
  45. package/dist/group/count-by.js +35 -0
  46. package/dist/group/count-by.js.map +1 -0
  47. package/dist/group/flat-group-by.d.ts +28 -0
  48. package/dist/group/flat-group-by.d.ts.map +1 -0
  49. package/dist/group/flat-group-by.js +30 -0
  50. package/dist/group/flat-group-by.js.map +1 -0
  51. package/dist/group/group-adjacent-by.d.ts +31 -0
  52. package/dist/group/group-adjacent-by.d.ts.map +1 -0
  53. package/dist/group/group-adjacent-by.js +50 -0
  54. package/dist/group/group-adjacent-by.js.map +1 -0
  55. package/dist/group/group-sort.d.ts +38 -0
  56. package/dist/group/group-sort.d.ts.map +1 -0
  57. package/dist/group/group-sort.js +49 -0
  58. package/dist/group/group-sort.js.map +1 -0
  59. package/dist/group/index-by.d.ts +33 -0
  60. package/dist/group/index-by.d.ts.map +1 -0
  61. package/dist/group/index-by.js +42 -0
  62. package/dist/group/index-by.js.map +1 -0
  63. package/dist/group/nested-map.d.ts +12 -0
  64. package/dist/group/nested-map.d.ts.map +1 -0
  65. package/dist/group/nested-map.js +2 -0
  66. package/dist/group/nested-map.js.map +1 -0
  67. package/dist/group/rollup-by.d.ts +62 -0
  68. package/dist/group/rollup-by.d.ts.map +1 -0
  69. package/dist/group/rollup-by.js +72 -0
  70. package/dist/group/rollup-by.js.map +1 -0
  71. package/dist/group/run-length-encode.d.ts +41 -0
  72. package/dist/group/run-length-encode.d.ts.map +1 -0
  73. package/dist/group/run-length-encode.js +66 -0
  74. package/dist/group/run-length-encode.js.map +1 -0
  75. package/dist/index.d.ts +32 -1
  76. package/dist/index.d.ts.map +1 -1
  77. package/dist/index.js +32 -1
  78. package/dist/index.js.map +1 -1
  79. package/dist/ordered/is-sorted.d.ts +33 -0
  80. package/dist/ordered/is-sorted.d.ts.map +1 -0
  81. package/dist/ordered/is-sorted.js +39 -0
  82. package/dist/ordered/is-sorted.js.map +1 -0
  83. package/dist/sample/sample-without-replacement.d.ts +26 -0
  84. package/dist/sample/sample-without-replacement.d.ts.map +1 -0
  85. package/dist/sample/sample-without-replacement.js +41 -0
  86. package/dist/sample/sample-without-replacement.js.map +1 -0
  87. package/dist/sample/shuffle.d.ts +2 -2
  88. package/dist/sample/shuffle.d.ts.map +1 -1
  89. package/dist/sample/shuffle.js +3 -3
  90. package/dist/sample/shuffle.js.map +1 -1
  91. package/dist/sample/weighted-choice-index.d.ts +29 -0
  92. package/dist/sample/weighted-choice-index.d.ts.map +1 -0
  93. package/dist/sample/weighted-choice-index.js +62 -0
  94. package/dist/sample/weighted-choice-index.js.map +1 -0
  95. package/dist/sample/weighted-choice.d.ts +28 -0
  96. package/dist/sample/weighted-choice.d.ts.map +1 -0
  97. package/dist/sample/weighted-choice.js +31 -0
  98. package/dist/sample/weighted-choice.js.map +1 -0
  99. package/dist/select/minmax.d.ts +52 -0
  100. package/dist/select/minmax.d.ts.map +1 -0
  101. package/dist/select/minmax.js +109 -0
  102. package/dist/select/minmax.js.map +1 -0
  103. package/dist/select/{quickselect.d.ts → quickselect-in-place.d.ts} +2 -2
  104. package/dist/select/quickselect-in-place.d.ts.map +1 -0
  105. package/dist/select/{quickselect.js → quickselect-in-place.js} +2 -2
  106. package/dist/select/quickselect-in-place.js.map +1 -0
  107. package/dist/sequence/_matching-runs.d.ts +16 -0
  108. package/dist/sequence/_matching-runs.d.ts.map +1 -0
  109. package/dist/sequence/_matching-runs.js +178 -0
  110. package/dist/sequence/_matching-runs.js.map +1 -0
  111. package/dist/sequence/common-prefix-length.d.ts +26 -0
  112. package/dist/sequence/common-prefix-length.d.ts.map +1 -0
  113. package/dist/sequence/common-prefix-length.js +34 -0
  114. package/dist/sequence/common-prefix-length.js.map +1 -0
  115. package/dist/sequence/diff-sequences.d.ts +59 -0
  116. package/dist/sequence/diff-sequences.d.ts.map +1 -0
  117. package/dist/sequence/diff-sequences.js +67 -0
  118. package/dist/sequence/diff-sequences.js.map +1 -0
  119. package/dist/sequence/levenshtein-distance.d.ts +43 -0
  120. package/dist/sequence/levenshtein-distance.d.ts.map +1 -0
  121. package/dist/sequence/levenshtein-distance.js +102 -0
  122. package/dist/sequence/levenshtein-distance.js.map +1 -0
  123. package/dist/sequence/longest-common-subsequence.d.ts +28 -0
  124. package/dist/sequence/longest-common-subsequence.d.ts.map +1 -0
  125. package/dist/sequence/longest-common-subsequence.js +39 -0
  126. package/dist/sequence/longest-common-subsequence.js.map +1 -0
  127. package/dist/sequence/longest-increasing-subsequence.d.ts +28 -0
  128. package/dist/sequence/longest-increasing-subsequence.d.ts.map +1 -0
  129. package/dist/sequence/longest-increasing-subsequence.js +47 -0
  130. package/dist/sequence/longest-increasing-subsequence.js.map +1 -0
  131. package/dist/sort/_sort-primitives.d.ts +6 -0
  132. package/dist/sort/_sort-primitives.d.ts.map +1 -0
  133. package/dist/sort/_sort-primitives.js +18 -0
  134. package/dist/sort/_sort-primitives.js.map +1 -0
  135. package/dist/sort/counting-sort.d.ts +40 -0
  136. package/dist/sort/counting-sort.d.ts.map +1 -0
  137. package/dist/sort/counting-sort.js +51 -0
  138. package/dist/sort/counting-sort.js.map +1 -0
  139. package/dist/sort/merge-sort.d.ts +26 -0
  140. package/dist/sort/merge-sort.d.ts.map +1 -0
  141. package/dist/sort/merge-sort.js +73 -0
  142. package/dist/sort/merge-sort.js.map +1 -0
  143. package/dist/sort/quick-sort-in-place.d.ts +35 -0
  144. package/dist/sort/quick-sort-in-place.d.ts.map +1 -0
  145. package/dist/sort/quick-sort-in-place.js +98 -0
  146. package/dist/sort/quick-sort-in-place.js.map +1 -0
  147. package/dist/sort/rank.d.ts +64 -0
  148. package/dist/sort/rank.d.ts.map +1 -0
  149. package/dist/sort/rank.js +107 -0
  150. package/dist/sort/rank.js.map +1 -0
  151. package/dist/sort/sort-range.d.ts.map +1 -1
  152. package/dist/sort/sort-range.js +1 -16
  153. package/dist/sort/sort-range.js.map +1 -1
  154. package/package.json +6 -6
  155. package/dist/select/quickselect.d.ts.map +0 -1
  156. package/dist/select/quickselect.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,72 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5c203e7: **Breaking:** two names change to follow the package's naming rules, with no
8
+ alias kept for the old ones.
9
+
10
+ - `quickselect` is now `quickselectInPlace`: the suffix says that it rearranges
11
+ the array it is given. Its signature and behaviour are unchanged.
12
+ - `ShuffleOptions.rand` is now `random`, typed `RandomFn` from `@ac-kit/core`,
13
+ the name every other sampling function in the package uses.
14
+
15
+ Migration: `quickselect(items, k, compare)` becomes
16
+ `quickselectInPlace(items, k, compare)`, and `shuffle(items, { rand })` becomes
17
+ `shuffle(items, { random: rand })`. A `rand` option is now an excess property
18
+ and a type error; untyped callers that keep passing it get `Math.random`.
19
+ - 5c203e7: New graph functions over `childrenOf`/`neighboursOf` callbacks (so
20
+ `@ac-kit/data`'s `Graph` and `DirectedGraph` drive them through `neighbors` and
21
+ `outNeighbors`), all iterative: `bfs(root, traits)`, the level-order walk whose
22
+ `onEnter(node, depth, parent)` gives shortest paths in edge count, with
23
+ `BfsWalkSkipChildren`/`BfsWalkStop`; `topologicalSort(roots, childrenOf,
24
+ options)`, Kahn's order, which throws a `GraphCycleError` carrying one `cycle`
25
+ instead of returning a partial order, with an optional work budget;
26
+ `connectedComponents(nodes, neighboursOf)`, where an edge listed from either end
27
+ counts both ways; `lowestCommonAncestor(a, b, parentOf)`; and
28
+ `floydWarshall(nodes, traits)`, all-pairs `distances` and `nextHops` tables
29
+ that allow negative edges and reject a negative cycle.
30
+
31
+ Sorting and selection: `mergeSort` (stable, O(n log n) guaranteed),
32
+ `quickSortInPlace` (three-way, O(log n) space, arrays and typed arrays),
33
+ `countingSort(items, valueOf, { min, max })`, `isSorted(items, compare, {
34
+ strict })`, and `minmax`/`minmaxBy`, both extremes in one pass (`NaN` keys
35
+ skipped by `minmaxBy`).
36
+
37
+ Grouping: `countBy`, `rollupBy`, `indexBy` (throws on a repeated key),
38
+ `flatGroupBy`, `flatRollupBy` and `groupSort`, with `groupBy`'s array of key
39
+ accessors and nested-`Map` result (`NestedMap`); `groupAdjacentBy` for
40
+ consecutive runs under any equality; `runLengthEncode`/`runLengthDecode`.
41
+
42
+ Sequences, over any array-like (strings included) with an
43
+ `EqualityComparisonStrategy` defaulting to `"strict"`: `levenshteinDistance(a,
44
+ b, { maxDistance })`, which answers `Infinity` past the bound in banded time;
45
+ `diffSequences`, a shortest keep/delete/insert script (Myers, linear space);
46
+ `longestCommonSubsequence`; `longestIncreasingSubsequence`; and
47
+ `commonPrefixLength`.
48
+
49
+ Combinatorics: `permutations`/`permutationsLazy` (Heap's order),
50
+ `powerSet`/`powerSetLazy` and `cartesianProduct`/`cartesianProductLazy`; the
51
+ eager forms throw a `RangeError` past the largest array length. Sampling:
52
+ `weightedChoice`/`weightedChoiceIndex` (`undefined`/`-1` when no weight is
53
+ positive) and `sampleWithoutReplacement`, O(size) whatever the input length.
54
+ - 5c203e7: `rank(values, compare, options)` and `rankBy(items, valueOf, options)` return
55
+ the 1-based rank of each value at its own position, as a `Float64Array`. Ties
56
+ share ranks by `options.ties`: `"average"` (the default), `"min"`, `"max"`,
57
+ `"dense"` or `"ordinal"` (input order). `rankBy` ties `-0` with `0` and gives a
58
+ `NaN` key a `NaN` rank, ranking the other items among themselves.
59
+
60
+ ### Patch Changes
61
+
62
+ - Updated dependencies [5c203e7]
63
+ - Updated dependencies [5c203e7]
64
+ - Updated dependencies [5c203e7]
65
+ - Updated dependencies [5c203e7]
66
+ - Updated dependencies [5c203e7]
67
+ - @ac-kit/core@0.14.0
68
+ - @ac-kit/data@0.6.0
69
+
3
70
  ## 0.6.0
4
71
 
5
72
  ### Minor Changes
package/README.md CHANGED
@@ -3,15 +3,16 @@
3
3
  Classic algorithms that work on **your** types, not on numbers.
4
4
 
5
5
  Nothing here assumes what an element is. Ordering, equality, scoring and
6
- neighbour expansion are all supplied as callbacks, so the same `quickselect`
7
- sorts your invoices by due date and your pixels by luminance, and the same graph
8
- search walks your dependency tree and your maze.
6
+ neighbour expansion are all supplied as callbacks, so the same
7
+ `quickselectInPlace` sorts your invoices by due date and your pixels by
8
+ luminance, and the same graph search walks your dependency tree and your maze.
9
9
 
10
10
  ```ts
11
- import { groupBy, quickselect, uniqBy } from "@ac-kit/algo";
11
+ import { groupBy, quickselectInPlace, uniqBy } from "@ac-kit/algo";
12
12
 
13
- // Order statistics without paying for a full sort — O(n) average.
14
- const median = quickselect(
13
+ // Order statistics without paying for a full sort — O(n) average. It
14
+ // rearranges the array it is given, hence the copy.
15
+ const median = quickselectInPlace(
15
16
  [...durations],
16
17
  durations.length >> 1,
17
18
  (a, b) => a - b,
@@ -35,6 +36,14 @@ const distinct = [...uniqBy(events, (event) => event.correlationId)];
35
36
  (or nothing), for an error message that names it. `hierarchyFromParents` turns rows with a key and a
36
37
  parent key (a chart's frame) into the `childrenOf` those take, as flat
37
38
  `Uint32Array` offsets and indices (d3 `stratify`).
39
+ - **Graph structure** — `bfs`, the level-order walk with depth and parent (the
40
+ shortest path in edge count), `topologicalSort` (Kahn's, throwing a
41
+ `GraphCycleError` that names one cycle rather than returning a partial
42
+ order), `connectedComponents` (union–find, so an edge listed from one end
43
+ counts both ways), `lowestCommonAncestor` over a `parentOf` callback, and
44
+ `floydWarshall`, all-pairs shortest paths with negative edges and next hops.
45
+ All iterative, over callbacks, so `@ac-kit/data`'s `Graph` and
46
+ `DirectedGraph` drive them through `neighbors`/`outNeighbors`.
38
47
  - **Recursion without a stack** — `runTrampoline` runs a recursive algorithm
39
48
  written as native synchronous generators (`const value = yield child`) on
40
49
  an explicit stack, so a hostile nesting depth costs heap, not a stack
@@ -49,7 +58,8 @@ const distinct = [...uniqBy(events, (event) => event.correlationId)];
49
58
  sorted numeric array or typed array with no comparator or allocation (and
50
59
  `bisectRightNumbersArray` for a whole array of values),
51
60
  `binarySearch` over any integer range driven by a predicate alone, plus
52
- membership testing against sorted, disjoint intervals.
61
+ membership testing against sorted, disjoint intervals. `isSorted` checks the
62
+ precondition they all assume.
53
63
  - **Fractional indexing** — `generateFractionalKeyBetween(lower, upper)`
54
64
  returns a string key that sorts strictly between two others (`null` for an
55
65
  open end), so a user-ordered list moves an item by writing one key;
@@ -58,19 +68,36 @@ const distinct = [...uniqBy(events, (event) => event.correlationId)];
58
68
  `FractionalKeyAlphabet`), sort with plain string comparison, grow
59
69
  logarithmically on appends and prepends, and are checked by
60
70
  `isFractionalKey`/`assertFractionalKey`.
61
- - **Selection** — `quickselect` for order statistics, `minBy`/`maxBy` for the
62
- extreme item by a derived key, `uniqueMinBy` for the smallest item under a
71
+ - **Selection** — `quickselectInPlace` for order statistics, `minBy`/`maxBy` for the
72
+ extreme item by a derived key, `minmax`/`minmaxBy` for both extremes in one
73
+ pass, `uniqueMinBy` for the smallest item under a
63
74
  comparator only when no other ties with it, `selectAt` for picking positions.
64
- - **Sorting** — `radixSort`, a stable, comparator-free sort over an integer key,
75
+ - **Sorting** — `mergeSort`, stable with an O(n log n) guarantee,
76
+ `quickSortInPlace`, three-way quicksort in O(log n) space, `countingSort`
77
+ over a small integer key range, `radixSort`, a stable, comparator-free sort over an integer key,
65
78
  `sortedIndices`, the stable permutation a comparator sorts values into
66
- (an argsort), to reorder parallel arrays or write results back in place, and
79
+ (an argsort), to reorder parallel arrays or write results back in place,
80
+ `rank` and `rankBy`, the 1-based rank of each value with ties by average,
81
+ min, max, dense or ordinal ranking (`NaN` keys left unranked), and
67
82
  `RadixIndexSorter`, the same argsort over a typed array of numbers by radix
68
83
  passes, with no allocation once warm (the depth sort a renderer redoes each
69
84
  frame).
70
- - **Combinatorics** — `combinations` and `combinationsLazy`, every `k`-subset
71
- of your items.
85
+ - **Combinatorics** — `combinations`, every `k`-subset of your items,
86
+ `permutations` (Heap's), `powerSet` and `cartesianProduct`, each with a
87
+ `…Lazy` generator for spaces too large to hold.
88
+ - **Sequences** — `levenshteinDistance` with an optional bound that cuts the
89
+ work to a band, `diffSequences`, a shortest keep/delete/insert script by
90
+ Myers' algorithm in linear space, `longestCommonSubsequence` from it,
91
+ `longestIncreasingSubsequence` by patience sorting, and
92
+ `commonPrefixLength` — over strings, arrays or any array-like, with your
93
+ equality.
72
94
  - **Grouping** — `groupBy` (nesting one `Map` level per accessor), `partition`,
73
- `partitionIndices`, `uniq` and `uniqBy`; `groupIndices(items, groupOf,
95
+ `partitionIndices`, `uniq` and `uniqBy`; the rest of SQL's `GROUP BY`:
96
+ `countBy`, `rollupBy` (an aggregate per group), `indexBy` (unique keys),
97
+ `flatGroupBy`/`flatRollupBy` (one row per key tuple) and `groupSort` (keys
98
+ by a value of their group); `groupAdjacentBy` for consecutive runs only
99
+ (`itertools.groupby`), and `runLengthEncode`/`runLengthDecode`;
100
+ `groupIndices(items, groupOf,
74
101
  groupCount)` groups positions by an integer group number into two flat
75
102
  `Uint32Array`s (offsets and indices, the CSR layout of an adjacency list or a
76
103
  parent → children table) by counting sort. Group numbers already in an array
@@ -83,7 +110,9 @@ const distinct = [...uniqBy(events, (event) => event.correlationId)];
83
110
  - **Shuffling** — `shuffle` (Fisher–Yates or Sattolo) with the random source
84
111
  injectable, so results can be made reproducible, and `spreadEvenly` to
85
112
  interleave two collections at evenly spaced positions; `choice` draws one
86
- element from an injectable random source. (`randomInteger` and
113
+ element from an injectable random source, `weightedChoice` and
114
+ `weightedChoiceIndex` one in proportion to a weight, and
115
+ `sampleWithoutReplacement` several distinct ones in O(size). (`randomInteger` and
87
116
  `randomBoolean` live in `@ac-kit/math-random`.)
88
117
 
89
118
  ## What's not included
@@ -0,0 +1,46 @@
1
+ /** The tuple type of one element from each of `Sets`, in order. */
2
+ export type CartesianTuple<Sets extends readonly Iterable<unknown>[]> = {
3
+ -readonly [I in keyof Sets]: Sets[I] extends Iterable<infer TElement> ? TElement : never;
4
+ };
5
+ /**
6
+ * Every tuple taking one element from each set — the eager form of
7
+ * {@link cartesianProductLazy}, in the same order. Each tuple is a fresh
8
+ * array.
9
+ *
10
+ * Time complexity: O(p · k) for `k` sets and `p` the product of their sizes.
11
+ * Memory: the same, for the result.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * cartesianProduct([["S", "M"], [1, 2]]);
16
+ * // [["S", 1], ["S", 2], ["M", 1], ["M", 2]]
17
+ * ```;
18
+ *
19
+ * @param sets - The sets, as an array of iterables rather than a rest
20
+ * parameter; each is read once, up front.
21
+ * @returns The `p` tuples; one empty tuple for no sets, none when a set is
22
+ * empty.
23
+ * @throws {RangeError} When `p` exceeds the largest array length.
24
+ */
25
+ export declare function cartesianProduct<const Sets extends readonly Iterable<unknown>[]>(sets: Sets): CartesianTuple<Sets>[];
26
+ /**
27
+ * Every tuple taking one element from each set, yielded one at a time — the
28
+ * odometer: the last set's element changes fastest, so the tuples come in
29
+ * lexicographic order of their positions (Python's `itertools.product`).
30
+ *
31
+ * Time complexity: O(k) per tuple for `k` sets. Memory: the sets' elements,
32
+ * read up front, since every set but the first is walked many times.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * for (const [size, colour] of cartesianProductLazy([sizes, colours])) {
37
+ * // every variant of a product
38
+ * }
39
+ * ```;
40
+ *
41
+ * @param sets - The sets, as an array of iterables; each is read once, up
42
+ * front.
43
+ * @returns The tuples; one empty tuple for no sets, none when a set is empty.
44
+ */
45
+ export declare function cartesianProductLazy<const Sets extends readonly Iterable<unknown>[]>(sets: Sets): Generator<CartesianTuple<Sets>, void, undefined>;
46
+ //# sourceMappingURL=cartesian-product.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cartesian-product.d.ts","sourceRoot":"","sources":["../../src/combinatorics/cartesian-product.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,MAAM,MAAM,cAAc,CAAC,IAAI,SAAS,SAAS,QAAQ,CAAC,OAAO,CAAC,EAAE,IAAI;IACvE,CAAC,UAAU,CAAC,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,SAAS,QAAQ,CAAC,MAAM,QAAQ,CAAC,GAClE,QAAQ,GACR,KAAK;CACR,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,gBAAgB,CAC/B,KAAK,CAAC,IAAI,SAAS,SAAS,QAAQ,CAAC,OAAO,CAAC,EAAE,EAC9C,IAAI,EAAE,IAAI,GAAG,cAAc,CAAC,IAAI,CAAC,EAAE,CAYpC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,oBAAoB,CACnC,KAAK,CAAC,IAAI,SAAS,SAAS,QAAQ,CAAC,OAAO,CAAC,EAAE,EAC9C,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,CAAC,CAM9D"}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Every tuple taking one element from each set — the eager form of
3
+ * {@link cartesianProductLazy}, in the same order. Each tuple is a fresh
4
+ * array.
5
+ *
6
+ * Time complexity: O(p · k) for `k` sets and `p` the product of their sizes.
7
+ * Memory: the same, for the result.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * cartesianProduct([["S", "M"], [1, 2]]);
12
+ * // [["S", 1], ["S", 2], ["M", 1], ["M", 2]]
13
+ * ```;
14
+ *
15
+ * @param sets - The sets, as an array of iterables rather than a rest
16
+ * parameter; each is read once, up front.
17
+ * @returns The `p` tuples; one empty tuple for no sets, none when a set is
18
+ * empty.
19
+ * @throws {RangeError} When `p` exceeds the largest array length.
20
+ */
21
+ export function cartesianProduct(sets) {
22
+ const pools = sets.map((set) => [...set]);
23
+ let count = 1;
24
+ for (const pool of pools) {
25
+ count *= pool.length;
26
+ }
27
+ if (count > 4294967295) {
28
+ throw new RangeError(`cartesianProduct: ${count} tuples exceed the largest array length; use cartesianProductLazy`);
29
+ }
30
+ return [...product_(pools)];
31
+ }
32
+ /**
33
+ * Every tuple taking one element from each set, yielded one at a time — the
34
+ * odometer: the last set's element changes fastest, so the tuples come in
35
+ * lexicographic order of their positions (Python's `itertools.product`).
36
+ *
37
+ * Time complexity: O(k) per tuple for `k` sets. Memory: the sets' elements,
38
+ * read up front, since every set but the first is walked many times.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * for (const [size, colour] of cartesianProductLazy([sizes, colours])) {
43
+ * // every variant of a product
44
+ * }
45
+ * ```;
46
+ *
47
+ * @param sets - The sets, as an array of iterables; each is read once, up
48
+ * front.
49
+ * @returns The tuples; one empty tuple for no sets, none when a set is empty.
50
+ */
51
+ export function cartesianProductLazy(sets) {
52
+ return product_(sets.map((set) => [...set]));
53
+ }
54
+ function* product_(pools) {
55
+ const count = pools.length;
56
+ for (const pool of pools) {
57
+ if (pool.length === 0) {
58
+ return;
59
+ }
60
+ }
61
+ const positions = new Uint32Array(count);
62
+ for (;;) {
63
+ const tuple = Array.from({ length: count });
64
+ for (let set = 0; set < count; set++) {
65
+ tuple[set] = pools[set][positions[set]];
66
+ }
67
+ yield tuple;
68
+ let set = count - 1;
69
+ while (set >= 0 && positions[set] === pools[set].length - 1) {
70
+ positions[set] = 0;
71
+ set--;
72
+ }
73
+ if (set < 0) {
74
+ return;
75
+ }
76
+ positions[set]++;
77
+ }
78
+ }
79
+ //# sourceMappingURL=cartesian-product.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cartesian-product.js","sourceRoot":"","sources":["../../src/combinatorics/cartesian-product.ts"],"names":[],"mappings":"AAOA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,gBAAgB,CAE9B,IAAU;IACX,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;IAC1C,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC;IACtB,CAAC;IACD,IAAI,KAAK,GAAG,UAAW,EAAE,CAAC;QACzB,MAAM,IAAI,UAAU,CACnB,qBAAqB,KAAK,mEAAmE,CAC7F,CAAC;IACH,CAAC;IACD,OAAO,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAA2B,CAAC;AACvD,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,oBAAoB,CAElC,IAAU;IACX,OAAO,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAI1C,CAAC;AACH,CAAC;AAED,QAAQ,CAAC,CAAC,QAAQ,CACjB,KAAsC;IAEtC,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC;IAC3B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvB,OAAO;QACR,CAAC;IACF,CAAC;IACD,MAAM,SAAS,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IACzC,SAAS,CAAC;QACT,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAU,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;QACrD,KAAK,IAAI,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC;YACtC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAE,CAAC,SAAS,CAAC,GAAG,CAAE,CAAC,CAAC;QAC3C,CAAC;QACD,MAAM,KAAK,CAAC;QAEZ,IAAI,GAAG,GAAG,KAAK,GAAG,CAAC,CAAC;QACpB,OAAO,GAAG,IAAI,CAAC,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,GAAG,CAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC9D,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACnB,GAAG,EAAE,CAAC;QACP,CAAC;QACD,IAAI,GAAG,GAAG,CAAC,EAAE,CAAC;YACb,OAAO;QACR,CAAC;QACD,SAAS,CAAC,GAAG,CAAE,EAAE,CAAC;IACnB,CAAC;AACF,CAAC"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Every ordering of `items` — the eager form of {@link permutationsLazy}, in the
3
+ * same order. Each permutation is a fresh array.
4
+ *
5
+ * Reach for it to try every order of a small set; there are `n!` of them, so
6
+ * past a handful of items use {@link permutationsLazy} and stop early.
7
+ *
8
+ * Time complexity: O(n! · n). Memory: the same, for the result.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * permutations([1, 2, 3]);
13
+ * // [[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]]
14
+ * ```;
15
+ *
16
+ * @param items - The items to order; equal items are not told apart, so repeats
17
+ * yield repeated permutations.
18
+ * @returns All `n!` permutations; one empty permutation for no items.
19
+ * @throws {RangeError} When `n!` exceeds the largest array length (`n > 12`).
20
+ */
21
+ export declare function permutations<T>(items: readonly T[]): T[][];
22
+ /**
23
+ * Every ordering of `items`, yielded one at a time — Heap's algorithm (1963),
24
+ * iterative: each permutation differs from the previous one by a single swap,
25
+ * so the next one costs O(1) amortised before its copy. Each yielded array is
26
+ * fresh and owned by the caller. The order is Heap's, not lexicographic.
27
+ *
28
+ * Time complexity: O(n) per permutation, for its copy. Memory: O(n).
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * for (const order of permutationsLazy(stops)) {
33
+ * if (isFeasible(order)) return order;
34
+ * }
35
+ * ```;
36
+ *
37
+ * @param items - The items to order; read once, up front.
38
+ * @returns The `n!` permutations; one empty permutation for no items.
39
+ */
40
+ export declare function permutationsLazy<T>(items: readonly T[]): Generator<T[], void, undefined>;
41
+ //# sourceMappingURL=permutations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permutations.d.ts","sourceRoot":"","sources":["../../src/combinatorics/permutations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,CAO1D;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAiB,gBAAgB,CAAC,CAAC,EAClC,KAAK,EAAE,SAAS,CAAC,EAAE,GACjB,SAAS,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAuBjC"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Every ordering of `items` — the eager form of {@link permutationsLazy}, in the
3
+ * same order. Each permutation is a fresh array.
4
+ *
5
+ * Reach for it to try every order of a small set; there are `n!` of them, so
6
+ * past a handful of items use {@link permutationsLazy} and stop early.
7
+ *
8
+ * Time complexity: O(n! · n). Memory: the same, for the result.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * permutations([1, 2, 3]);
13
+ * // [[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]]
14
+ * ```;
15
+ *
16
+ * @param items - The items to order; equal items are not told apart, so repeats
17
+ * yield repeated permutations.
18
+ * @returns All `n!` permutations; one empty permutation for no items.
19
+ * @throws {RangeError} When `n!` exceeds the largest array length (`n > 12`).
20
+ */
21
+ export function permutations(items) {
22
+ if (items.length > 12) {
23
+ throw new RangeError(`permutations: ${items.length}! permutations exceed the largest array length; use permutationsLazy`);
24
+ }
25
+ return [...permutationsLazy(items)];
26
+ }
27
+ /**
28
+ * Every ordering of `items`, yielded one at a time — Heap's algorithm (1963),
29
+ * iterative: each permutation differs from the previous one by a single swap,
30
+ * so the next one costs O(1) amortised before its copy. Each yielded array is
31
+ * fresh and owned by the caller. The order is Heap's, not lexicographic.
32
+ *
33
+ * Time complexity: O(n) per permutation, for its copy. Memory: O(n).
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * for (const order of permutationsLazy(stops)) {
38
+ * if (isFeasible(order)) return order;
39
+ * }
40
+ * ```;
41
+ *
42
+ * @param items - The items to order; read once, up front.
43
+ * @returns The `n!` permutations; one empty permutation for no items.
44
+ */
45
+ export function* permutationsLazy(items) {
46
+ const current = items.slice();
47
+ const length = current.length;
48
+ // counters[i]: how many swaps level i has made — the explicit form of the
49
+ // recursion's loop index at each depth.
50
+ const counters = new Uint32Array(length);
51
+ yield current.slice();
52
+ let level = 1;
53
+ while (level < length) {
54
+ const counter = counters[level];
55
+ if (counter < level) {
56
+ const other = level % 2 === 0 ? 0 : counter;
57
+ const swapped = current[other];
58
+ current[other] = current[level];
59
+ current[level] = swapped;
60
+ yield current.slice();
61
+ counters[level] = counter + 1;
62
+ level = 1;
63
+ }
64
+ else {
65
+ counters[level] = 0;
66
+ level++;
67
+ }
68
+ }
69
+ }
70
+ //# sourceMappingURL=permutations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permutations.js","sourceRoot":"","sources":["../../src/combinatorics/permutations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,YAAY,CAAI,KAAmB;IAClD,IAAI,KAAK,CAAC,MAAM,GAAG,EAAE,EAAE,CAAC;QACvB,MAAM,IAAI,UAAU,CACnB,iBAAiB,KAAK,CAAC,MAAM,sEAAsE,CACnG,CAAC;IACH,CAAC;IACD,OAAO,CAAC,GAAG,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC;AACrC,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,SAAS,CAAC,CAAC,gBAAgB,CAChC,KAAmB;IAEnB,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;IAC9B,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAC9B,0EAA0E;IAC1E,wCAAwC;IACxC,MAAM,QAAQ,GAAG,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC;IACzC,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;IACtB,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,OAAO,KAAK,GAAG,MAAM,EAAE,CAAC;QACvB,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAE,CAAC;QACjC,IAAI,OAAO,GAAG,KAAK,EAAE,CAAC;YACrB,MAAM,KAAK,GAAG,KAAK,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;YAC5C,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAE,CAAC;YAChC,OAAO,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,KAAK,CAAE,CAAC;YACjC,OAAO,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC;YACzB,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;YACtB,QAAQ,CAAC,KAAK,CAAC,GAAG,OAAO,GAAG,CAAC,CAAC;YAC9B,KAAK,GAAG,CAAC,CAAC;QACX,CAAC;aAAM,CAAC;YACP,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACpB,KAAK,EAAE,CAAC;QACT,CAAC;IACF,CAAC;AACF,CAAC"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Every subset of `items` — the eager form of {@link powerSetLazy}, in the same
3
+ * order. Each subset is a fresh array.
4
+ *
5
+ * There are `2ⁿ` subsets, so past a handful of items use {@link powerSetLazy}
6
+ * and stop early.
7
+ *
8
+ * Time complexity: O(2ⁿ · n). Memory: the same, for the result.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * powerSet(["a", "b", "c"]);
13
+ * // [[], ["a"], ["b"], ["a", "b"], ["c"], ["a", "c"], ["b", "c"], ["a", "b", "c"]]
14
+ * ```;
15
+ *
16
+ * @param items - The items; equal items are not told apart.
17
+ * @returns All `2ⁿ` subsets, each in the order its items appear in `items`.
18
+ * @throws {RangeError} When `2ⁿ` exceeds the largest array length (`n > 31`).
19
+ */
20
+ export declare function powerSet<T>(items: readonly T[]): T[][];
21
+ /**
22
+ * Every subset of `items`, yielded one at a time, by a binary counter: subset
23
+ * number `c` holds `items[i]` exactly when bit `i` of `c` is set, so the empty
24
+ * subset comes first, the full one last, and each subset's items keep their
25
+ * order in `items`. The counter is an array of bits rather than a number, so
26
+ * any length works for as long as the caller keeps pulling.
27
+ *
28
+ * Time complexity: O(n) per subset, for its copy; the counter's increment is
29
+ * O(1) amortised. Memory: O(n).
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * [...powerSetLazy([1, 2])]; // [[], [1], [2], [1, 2]]
34
+ * ```;
35
+ *
36
+ * @param items - The items; read once, up front.
37
+ * @returns The `2ⁿ` subsets.
38
+ */
39
+ export declare function powerSetLazy<T>(items: readonly T[]): Generator<T[], void, undefined>;
40
+ //# sourceMappingURL=power-set.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"power-set.d.ts","sourceRoot":"","sources":["../../src/combinatorics/power-set.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,CAOtD;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAiB,YAAY,CAAC,CAAC,EAC9B,KAAK,EAAE,SAAS,CAAC,EAAE,GACjB,SAAS,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAuBjC"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Every subset of `items` — the eager form of {@link powerSetLazy}, in the same
3
+ * order. Each subset is a fresh array.
4
+ *
5
+ * There are `2ⁿ` subsets, so past a handful of items use {@link powerSetLazy}
6
+ * and stop early.
7
+ *
8
+ * Time complexity: O(2ⁿ · n). Memory: the same, for the result.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * powerSet(["a", "b", "c"]);
13
+ * // [[], ["a"], ["b"], ["a", "b"], ["c"], ["a", "c"], ["b", "c"], ["a", "b", "c"]]
14
+ * ```;
15
+ *
16
+ * @param items - The items; equal items are not told apart.
17
+ * @returns All `2ⁿ` subsets, each in the order its items appear in `items`.
18
+ * @throws {RangeError} When `2ⁿ` exceeds the largest array length (`n > 31`).
19
+ */
20
+ export function powerSet(items) {
21
+ if (items.length > 31) {
22
+ throw new RangeError(`powerSet: 2^${items.length} subsets exceed the largest array length; use powerSetLazy`);
23
+ }
24
+ return [...powerSetLazy(items)];
25
+ }
26
+ /**
27
+ * Every subset of `items`, yielded one at a time, by a binary counter: subset
28
+ * number `c` holds `items[i]` exactly when bit `i` of `c` is set, so the empty
29
+ * subset comes first, the full one last, and each subset's items keep their
30
+ * order in `items`. The counter is an array of bits rather than a number, so
31
+ * any length works for as long as the caller keeps pulling.
32
+ *
33
+ * Time complexity: O(n) per subset, for its copy; the counter's increment is
34
+ * O(1) amortised. Memory: O(n).
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * [...powerSetLazy([1, 2])]; // [[], [1], [2], [1, 2]]
39
+ * ```;
40
+ *
41
+ * @param items - The items; read once, up front.
42
+ * @returns The `2ⁿ` subsets.
43
+ */
44
+ export function* powerSetLazy(items) {
45
+ const pool = items.slice();
46
+ const length = pool.length;
47
+ const bits = new Uint8Array(length);
48
+ for (;;) {
49
+ const subset = [];
50
+ for (let index = 0; index < length; index++) {
51
+ if (bits[index] === 1) {
52
+ subset.push(pool[index]);
53
+ }
54
+ }
55
+ yield subset;
56
+ let index = 0;
57
+ while (index < length && bits[index] === 1) {
58
+ bits[index] = 0;
59
+ index++;
60
+ }
61
+ if (index === length) {
62
+ return;
63
+ }
64
+ bits[index] = 1;
65
+ }
66
+ }
67
+ //# sourceMappingURL=power-set.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"power-set.js","sourceRoot":"","sources":["../../src/combinatorics/power-set.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,QAAQ,CAAI,KAAmB;IAC9C,IAAI,KAAK,CAAC,MAAM,GAAG,EAAE,EAAE,CAAC;QACvB,MAAM,IAAI,UAAU,CACnB,eAAe,KAAK,CAAC,MAAM,4DAA4D,CACvF,CAAC;IACH,CAAC;IACD,OAAO,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;AACjC,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,SAAS,CAAC,CAAC,YAAY,CAC5B,KAAmB;IAEnB,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;IAC3B,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;IAC3B,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACpC,SAAS,CAAC;QACT,MAAM,MAAM,GAAQ,EAAE,CAAC;QACvB,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;YAC7C,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC,CAAC;YAC3B,CAAC;QACF,CAAC;QACD,MAAM,MAAM,CAAC;QAEb,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,OAAO,KAAK,GAAG,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAChB,KAAK,EAAE,CAAC;QACT,CAAC;QACD,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;YACtB,OAAO;QACR,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACjB,CAAC;AACF,CAAC"}
@@ -0,0 +1,66 @@
1
+ /** Continue walking the graph, queueing the children of this node. */
2
+ export declare const BfsWalkContinue: unique symbol;
3
+ /** Do not queue the children of this node, but continue walking the graph. */
4
+ export declare const BfsWalkSkipChildren: unique symbol;
5
+ /** Stop walking the graph immediately, returning `true` from {@link bfs}. */
6
+ export declare const BfsWalkStop: unique symbol;
7
+ /** The return value of {@link BfsTraits.onEnter} to control the walk. */
8
+ export type BfsWalkControl = typeof BfsWalkContinue | typeof BfsWalkSkipChildren | typeof BfsWalkStop;
9
+ export type BfsTraits<TNode> = {
10
+ /**
11
+ * Returns the successors of a node, or `undefined`/empty for a leaf. Called
12
+ * at most once per entered node, and not for a node whose `onEnter` skips its
13
+ * children or stops the walk.
14
+ */
15
+ childrenOf: (node: TNode) => Iterable<TNode> | undefined;
16
+ /**
17
+ * Called on entering a node, level after level. `depth` is the number of
18
+ * edges from the root — with {@link BfsTraits.seen}, the length of a shortest
19
+ * path to the node in edge count — and `parent` the node it was reached from
20
+ * (`undefined` for the root), so recording the parents gives those shortest
21
+ * paths. Returning `undefined` is treated as {@link BfsWalkContinue}.
22
+ */
23
+ onEnter?: (node: TNode, depth: number, parent: TNode | undefined) => BfsWalkControl | undefined;
24
+ /**
25
+ * Marks the nodes already reached, for a graph in which a node is reachable
26
+ * twice (a cycle or a shared descendant). A node is marked when it is first
27
+ * queued, so it is entered once, from the shallowest level. Omit for a tree,
28
+ * where no node is reachable twice and the bookkeeping would be wasted.
29
+ */
30
+ seen?: Set<TNode>;
31
+ };
32
+ /**
33
+ * Walks a graph or tree breadth-first: the root, then every node one edge away,
34
+ * then every node two edges away, and so on — level order. The counterpart of
35
+ * `dfs` with the same `childrenOf` shape, and the search that finds a shortest
36
+ * path in edge count when every edge costs the same (use `aStar` when edges
37
+ * have costs).
38
+ *
39
+ * Iterative, level by level, so a deep graph cannot overflow the stack. Nodes
40
+ * are compared by identity in {@link BfsTraits.seen} (`Set` semantics).
41
+ *
42
+ * Time complexity: O(V + E) for the nodes and edges reached. Memory: O(w) for
43
+ * the widest level `w`, plus `seen`. Without {@link BfsTraits.seen}, a cyclic
44
+ * graph does not terminate — pass a `Set` whenever a cycle is possible.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * // Shortest path in edge count, from the parents of a breadth-first walk.
49
+ * const parents = new Map<string, string | undefined>();
50
+ * bfs("a", {
51
+ * childrenOf: (node) => graph.outNeighbors(node),
52
+ * seen: new Set(),
53
+ * onEnter: (node, _depth, parent) => {
54
+ * parents.set(node, parent);
55
+ * return node === "goal" ? BfsWalkStop : undefined;
56
+ * },
57
+ * });
58
+ * ```;
59
+ *
60
+ * @param root - The node to start walking from.
61
+ * @param traits - How to traverse, and what to do at each node.
62
+ * @returns `true` if the walk was stopped early via {@link BfsWalkStop},
63
+ * `false` if it ran to completion (or `root` was already in `seen`).
64
+ */
65
+ export declare function bfs<TNode>(root: TNode, traits: BfsTraits<TNode>): boolean;
66
+ //# sourceMappingURL=bfs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bfs.d.ts","sourceRoot":"","sources":["../../src/graph/bfs.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,eAAO,MAAM,eAAe,eAA4B,CAAC;AACzD,8EAA8E;AAC9E,eAAO,MAAM,mBAAmB,eAAgC,CAAC;AACjE,6EAA6E;AAC7E,eAAO,MAAM,WAAW,eAAwB,CAAC;AAEjD,yEAAyE;AACzE,MAAM,MAAM,cAAc,GACvB,OAAO,eAAe,GACtB,OAAO,mBAAmB,GAC1B,OAAO,WAAW,CAAC;AAEtB,MAAM,MAAM,SAAS,CAAC,KAAK,IAAI;IAC9B;;;;OAIG;IACH,UAAU,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,QAAQ,CAAC,KAAK,CAAC,GAAG,SAAS,CAAC;IAEzD;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,CACT,IAAI,EAAE,KAAK,EACX,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,KAAK,GAAG,SAAS,KACrB,cAAc,GAAG,SAAS,CAAC;IAEhC;;;;;OAKG;IACH,IAAI,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,CAAC,KAAK,CAAC,GAAG,OAAO,CAuDzE"}