@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.
- package/CHANGELOG.md +67 -0
- package/README.md +44 -15
- package/dist/combinatorics/cartesian-product.d.ts +46 -0
- package/dist/combinatorics/cartesian-product.d.ts.map +1 -0
- package/dist/combinatorics/cartesian-product.js +79 -0
- package/dist/combinatorics/cartesian-product.js.map +1 -0
- package/dist/combinatorics/permutations.d.ts +41 -0
- package/dist/combinatorics/permutations.d.ts.map +1 -0
- package/dist/combinatorics/permutations.js +70 -0
- package/dist/combinatorics/permutations.js.map +1 -0
- package/dist/combinatorics/power-set.d.ts +40 -0
- package/dist/combinatorics/power-set.d.ts.map +1 -0
- package/dist/combinatorics/power-set.js +67 -0
- package/dist/combinatorics/power-set.js.map +1 -0
- package/dist/graph/bfs.d.ts +66 -0
- package/dist/graph/bfs.d.ts.map +1 -0
- package/dist/graph/bfs.js +89 -0
- package/dist/graph/bfs.js.map +1 -0
- package/dist/graph/connected-components.d.ts +35 -0
- package/dist/graph/connected-components.d.ts.map +1 -0
- package/dist/graph/connected-components.js +75 -0
- package/dist/graph/connected-components.js.map +1 -0
- package/dist/graph/floyd-warshall.d.ts +67 -0
- package/dist/graph/floyd-warshall.d.ts.map +1 -0
- package/dist/graph/floyd-warshall.js +106 -0
- package/dist/graph/floyd-warshall.js.map +1 -0
- package/dist/graph/graph-cycle-error.d.ts +16 -0
- package/dist/graph/graph-cycle-error.d.ts.map +1 -0
- package/dist/graph/graph-cycle-error.js +20 -0
- package/dist/graph/graph-cycle-error.js.map +1 -0
- package/dist/graph/lowest-common-ancestor.d.ts +32 -0
- package/dist/graph/lowest-common-ancestor.d.ts.map +1 -0
- package/dist/graph/lowest-common-ancestor.js +56 -0
- package/dist/graph/lowest-common-ancestor.js.map +1 -0
- package/dist/graph/topological-sort.d.ts +51 -0
- package/dist/graph/topological-sort.d.ts.map +1 -0
- package/dist/graph/topological-sort.js +124 -0
- package/dist/graph/topological-sort.js.map +1 -0
- package/dist/group/_nest-by.d.ts +19 -0
- package/dist/group/_nest-by.d.ts.map +1 -0
- package/dist/group/_nest-by.js +85 -0
- package/dist/group/_nest-by.js.map +1 -0
- package/dist/group/count-by.d.ts +31 -0
- package/dist/group/count-by.d.ts.map +1 -0
- package/dist/group/count-by.js +35 -0
- package/dist/group/count-by.js.map +1 -0
- package/dist/group/flat-group-by.d.ts +28 -0
- package/dist/group/flat-group-by.d.ts.map +1 -0
- package/dist/group/flat-group-by.js +30 -0
- package/dist/group/flat-group-by.js.map +1 -0
- package/dist/group/group-adjacent-by.d.ts +31 -0
- package/dist/group/group-adjacent-by.d.ts.map +1 -0
- package/dist/group/group-adjacent-by.js +50 -0
- package/dist/group/group-adjacent-by.js.map +1 -0
- package/dist/group/group-sort.d.ts +38 -0
- package/dist/group/group-sort.d.ts.map +1 -0
- package/dist/group/group-sort.js +49 -0
- package/dist/group/group-sort.js.map +1 -0
- package/dist/group/index-by.d.ts +33 -0
- package/dist/group/index-by.d.ts.map +1 -0
- package/dist/group/index-by.js +42 -0
- package/dist/group/index-by.js.map +1 -0
- package/dist/group/nested-map.d.ts +12 -0
- package/dist/group/nested-map.d.ts.map +1 -0
- package/dist/group/nested-map.js +2 -0
- package/dist/group/nested-map.js.map +1 -0
- package/dist/group/rollup-by.d.ts +62 -0
- package/dist/group/rollup-by.d.ts.map +1 -0
- package/dist/group/rollup-by.js +72 -0
- package/dist/group/rollup-by.js.map +1 -0
- package/dist/group/run-length-encode.d.ts +41 -0
- package/dist/group/run-length-encode.d.ts.map +1 -0
- package/dist/group/run-length-encode.js +66 -0
- package/dist/group/run-length-encode.js.map +1 -0
- package/dist/index.d.ts +32 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +32 -1
- package/dist/index.js.map +1 -1
- package/dist/ordered/is-sorted.d.ts +33 -0
- package/dist/ordered/is-sorted.d.ts.map +1 -0
- package/dist/ordered/is-sorted.js +39 -0
- package/dist/ordered/is-sorted.js.map +1 -0
- package/dist/sample/sample-without-replacement.d.ts +26 -0
- package/dist/sample/sample-without-replacement.d.ts.map +1 -0
- package/dist/sample/sample-without-replacement.js +41 -0
- package/dist/sample/sample-without-replacement.js.map +1 -0
- package/dist/sample/shuffle.d.ts +2 -2
- package/dist/sample/shuffle.d.ts.map +1 -1
- package/dist/sample/shuffle.js +3 -3
- package/dist/sample/shuffle.js.map +1 -1
- package/dist/sample/weighted-choice-index.d.ts +29 -0
- package/dist/sample/weighted-choice-index.d.ts.map +1 -0
- package/dist/sample/weighted-choice-index.js +62 -0
- package/dist/sample/weighted-choice-index.js.map +1 -0
- package/dist/sample/weighted-choice.d.ts +28 -0
- package/dist/sample/weighted-choice.d.ts.map +1 -0
- package/dist/sample/weighted-choice.js +31 -0
- package/dist/sample/weighted-choice.js.map +1 -0
- package/dist/select/minmax.d.ts +52 -0
- package/dist/select/minmax.d.ts.map +1 -0
- package/dist/select/minmax.js +109 -0
- package/dist/select/minmax.js.map +1 -0
- package/dist/select/{quickselect.d.ts → quickselect-in-place.d.ts} +2 -2
- package/dist/select/quickselect-in-place.d.ts.map +1 -0
- package/dist/select/{quickselect.js → quickselect-in-place.js} +2 -2
- package/dist/select/quickselect-in-place.js.map +1 -0
- package/dist/sequence/_matching-runs.d.ts +16 -0
- package/dist/sequence/_matching-runs.d.ts.map +1 -0
- package/dist/sequence/_matching-runs.js +178 -0
- package/dist/sequence/_matching-runs.js.map +1 -0
- package/dist/sequence/common-prefix-length.d.ts +26 -0
- package/dist/sequence/common-prefix-length.d.ts.map +1 -0
- package/dist/sequence/common-prefix-length.js +34 -0
- package/dist/sequence/common-prefix-length.js.map +1 -0
- package/dist/sequence/diff-sequences.d.ts +59 -0
- package/dist/sequence/diff-sequences.d.ts.map +1 -0
- package/dist/sequence/diff-sequences.js +67 -0
- package/dist/sequence/diff-sequences.js.map +1 -0
- package/dist/sequence/levenshtein-distance.d.ts +43 -0
- package/dist/sequence/levenshtein-distance.d.ts.map +1 -0
- package/dist/sequence/levenshtein-distance.js +102 -0
- package/dist/sequence/levenshtein-distance.js.map +1 -0
- package/dist/sequence/longest-common-subsequence.d.ts +28 -0
- package/dist/sequence/longest-common-subsequence.d.ts.map +1 -0
- package/dist/sequence/longest-common-subsequence.js +39 -0
- package/dist/sequence/longest-common-subsequence.js.map +1 -0
- package/dist/sequence/longest-increasing-subsequence.d.ts +28 -0
- package/dist/sequence/longest-increasing-subsequence.d.ts.map +1 -0
- package/dist/sequence/longest-increasing-subsequence.js +47 -0
- package/dist/sequence/longest-increasing-subsequence.js.map +1 -0
- package/dist/sort/_sort-primitives.d.ts +6 -0
- package/dist/sort/_sort-primitives.d.ts.map +1 -0
- package/dist/sort/_sort-primitives.js +18 -0
- package/dist/sort/_sort-primitives.js.map +1 -0
- package/dist/sort/counting-sort.d.ts +40 -0
- package/dist/sort/counting-sort.d.ts.map +1 -0
- package/dist/sort/counting-sort.js +51 -0
- package/dist/sort/counting-sort.js.map +1 -0
- package/dist/sort/merge-sort.d.ts +26 -0
- package/dist/sort/merge-sort.d.ts.map +1 -0
- package/dist/sort/merge-sort.js +73 -0
- package/dist/sort/merge-sort.js.map +1 -0
- package/dist/sort/quick-sort-in-place.d.ts +35 -0
- package/dist/sort/quick-sort-in-place.d.ts.map +1 -0
- package/dist/sort/quick-sort-in-place.js +98 -0
- package/dist/sort/quick-sort-in-place.js.map +1 -0
- package/dist/sort/rank.d.ts +64 -0
- package/dist/sort/rank.d.ts.map +1 -0
- package/dist/sort/rank.js +107 -0
- package/dist/sort/rank.js.map +1 -0
- package/dist/sort/sort-range.d.ts.map +1 -1
- package/dist/sort/sort-range.js +1 -16
- package/dist/sort/sort-range.js.map +1 -1
- package/package.json +6 -6
- package/dist/select/quickselect.d.ts.map +0 -1
- package/dist/select/quickselect.js.map +0 -1
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/** Continue walking the graph, queueing the children of this node. */
|
|
2
|
+
export const BfsWalkContinue = Symbol("BfsWalkContinue");
|
|
3
|
+
/** Do not queue the children of this node, but continue walking the graph. */
|
|
4
|
+
export const BfsWalkSkipChildren = Symbol("BfsWalkSkipChildren");
|
|
5
|
+
/** Stop walking the graph immediately, returning `true` from {@link bfs}. */
|
|
6
|
+
export const BfsWalkStop = Symbol("BfsWalkStop");
|
|
7
|
+
/**
|
|
8
|
+
* Walks a graph or tree breadth-first: the root, then every node one edge away,
|
|
9
|
+
* then every node two edges away, and so on — level order. The counterpart of
|
|
10
|
+
* `dfs` with the same `childrenOf` shape, and the search that finds a shortest
|
|
11
|
+
* path in edge count when every edge costs the same (use `aStar` when edges
|
|
12
|
+
* have costs).
|
|
13
|
+
*
|
|
14
|
+
* Iterative, level by level, so a deep graph cannot overflow the stack. Nodes
|
|
15
|
+
* are compared by identity in {@link BfsTraits.seen} (`Set` semantics).
|
|
16
|
+
*
|
|
17
|
+
* Time complexity: O(V + E) for the nodes and edges reached. Memory: O(w) for
|
|
18
|
+
* the widest level `w`, plus `seen`. Without {@link BfsTraits.seen}, a cyclic
|
|
19
|
+
* graph does not terminate — pass a `Set` whenever a cycle is possible.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* // Shortest path in edge count, from the parents of a breadth-first walk.
|
|
24
|
+
* const parents = new Map<string, string | undefined>();
|
|
25
|
+
* bfs("a", {
|
|
26
|
+
* childrenOf: (node) => graph.outNeighbors(node),
|
|
27
|
+
* seen: new Set(),
|
|
28
|
+
* onEnter: (node, _depth, parent) => {
|
|
29
|
+
* parents.set(node, parent);
|
|
30
|
+
* return node === "goal" ? BfsWalkStop : undefined;
|
|
31
|
+
* },
|
|
32
|
+
* });
|
|
33
|
+
* ```;
|
|
34
|
+
*
|
|
35
|
+
* @param root - The node to start walking from.
|
|
36
|
+
* @param traits - How to traverse, and what to do at each node.
|
|
37
|
+
* @returns `true` if the walk was stopped early via {@link BfsWalkStop},
|
|
38
|
+
* `false` if it ran to completion (or `root` was already in `seen`).
|
|
39
|
+
*/
|
|
40
|
+
export function bfs(root, traits) {
|
|
41
|
+
const { childrenOf, onEnter, seen } = traits;
|
|
42
|
+
if (seen !== undefined) {
|
|
43
|
+
if (seen.has(root)) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
seen.add(root);
|
|
47
|
+
}
|
|
48
|
+
let level = [root];
|
|
49
|
+
let parents = [undefined];
|
|
50
|
+
let nextLevel = [];
|
|
51
|
+
let nextParents = [];
|
|
52
|
+
for (let depth = 0; level.length > 0; depth++) {
|
|
53
|
+
for (let index = 0; index < level.length; index++) {
|
|
54
|
+
const node = level[index];
|
|
55
|
+
const control = onEnter?.(node, depth, parents[index]) ?? BfsWalkContinue;
|
|
56
|
+
if (control === BfsWalkStop) {
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
if (control === BfsWalkSkipChildren) {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const children = childrenOf(node);
|
|
63
|
+
if (children === undefined) {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
for (const child of children) {
|
|
67
|
+
if (seen !== undefined) {
|
|
68
|
+
if (seen.has(child)) {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
seen.add(child);
|
|
72
|
+
}
|
|
73
|
+
nextLevel.push(child);
|
|
74
|
+
nextParents.push(node);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Swap the two level buffers so neither is reallocated per level.
|
|
78
|
+
const doneLevel = level;
|
|
79
|
+
const doneParents = parents;
|
|
80
|
+
level = nextLevel;
|
|
81
|
+
parents = nextParents;
|
|
82
|
+
nextLevel = doneLevel;
|
|
83
|
+
nextParents = doneParents;
|
|
84
|
+
nextLevel.length = 0;
|
|
85
|
+
nextParents.length = 0;
|
|
86
|
+
}
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
//# sourceMappingURL=bfs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"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E,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;gBAC7B,OAAO,IAAI,CAAC;YACb,CAAC;YACD,IAAI,OAAO,KAAK,mBAAmB,EAAE,CAAC;gBACrC,SAAS;YACV,CAAC;YAED,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;YAClC,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;gBAC5B,SAAS;YACV,CAAC;YACD,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE,CAAC;gBAC9B,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;oBACxB,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;wBACrB,SAAS;oBACV,CAAC;oBACD,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;gBACjB,CAAC;gBACD,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBACtB,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACxB,CAAC;QACF,CAAC;QAED,kEAAkE;QAClE,MAAM,SAAS,GAAG,KAAK,CAAC;QACxB,MAAM,WAAW,GAAG,OAAO,CAAC;QAC5B,KAAK,GAAG,SAAS,CAAC;QAClB,OAAO,GAAG,WAAW,CAAC;QACtB,SAAS,GAAG,SAAS,CAAC;QACtB,WAAW,GAAG,WAAW,CAAC;QAC1B,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;QACrB,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC;IACxB,CAAC;IAED,OAAO,KAAK,CAAC;AACd,CAAC"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { DefinedValue } from "@ac-kit/core";
|
|
2
|
+
/**
|
|
3
|
+
* Partitions an undirected graph into its connected components: the largest
|
|
4
|
+
* sets of nodes in which every node can reach every other.
|
|
5
|
+
*
|
|
6
|
+
* Each edge counts in both directions however it is listed, so a neighbour list
|
|
7
|
+
* need only name an edge from one of its two ends; handing in a directed
|
|
8
|
+
* graph's out-neighbours therefore gives its weakly connected components.
|
|
9
|
+
* Union–find over the edges (`StaticDisjointSet` from `@ac-kit/data`), so the
|
|
10
|
+
* result does not depend on the order edges are read in, and no deep graph can
|
|
11
|
+
* overflow the stack.
|
|
12
|
+
*
|
|
13
|
+
* The components come in the order of their first node, and the nodes of each
|
|
14
|
+
* in the order they first appear: `nodes` in order, then any node only a
|
|
15
|
+
* neighbour list names, where it is first named. Nodes are compared by identity
|
|
16
|
+
* (`Map` semantics, so `NaN` equals `NaN`); `neighboursOf` is called once per
|
|
17
|
+
* node, its iterable read once.
|
|
18
|
+
*
|
|
19
|
+
* Time complexity: O((V + E) · α(V)), effectively linear. Memory: O(V).
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* const graph = new Graph<string>();
|
|
24
|
+
* // …
|
|
25
|
+
* connectedComponents(graph.nodes(), (node) => graph.neighbors(node));
|
|
26
|
+
* ```;
|
|
27
|
+
*
|
|
28
|
+
* @param nodes - The nodes of the graph; a repeated one counts once. A node
|
|
29
|
+
* left out is still found when a neighbour list names it.
|
|
30
|
+
* @param neighboursOf - The neighbours of a node, or `undefined` for none.
|
|
31
|
+
* @returns The components, each a fresh array of its nodes.
|
|
32
|
+
* @throws Whatever `neighboursOf` or an iterator throws.
|
|
33
|
+
*/
|
|
34
|
+
export declare function connectedComponents<TNode extends DefinedValue>(nodes: Iterable<TNode>, neighboursOf: (node: TNode) => Iterable<TNode> | undefined): TNode[][];
|
|
35
|
+
//# sourceMappingURL=connected-components.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connected-components.d.ts","sourceRoot":"","sources":["../../src/graph/connected-components.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAGjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,SAAS,YAAY,EAC7D,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,EACtB,YAAY,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,QAAQ,CAAC,KAAK,CAAC,GAAG,SAAS,GACxD,KAAK,EAAE,EAAE,CA0CX"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { StaticDisjointSet } from "@ac-kit/data";
|
|
2
|
+
/**
|
|
3
|
+
* Partitions an undirected graph into its connected components: the largest
|
|
4
|
+
* sets of nodes in which every node can reach every other.
|
|
5
|
+
*
|
|
6
|
+
* Each edge counts in both directions however it is listed, so a neighbour list
|
|
7
|
+
* need only name an edge from one of its two ends; handing in a directed
|
|
8
|
+
* graph's out-neighbours therefore gives its weakly connected components.
|
|
9
|
+
* Union–find over the edges (`StaticDisjointSet` from `@ac-kit/data`), so the
|
|
10
|
+
* result does not depend on the order edges are read in, and no deep graph can
|
|
11
|
+
* overflow the stack.
|
|
12
|
+
*
|
|
13
|
+
* The components come in the order of their first node, and the nodes of each
|
|
14
|
+
* in the order they first appear: `nodes` in order, then any node only a
|
|
15
|
+
* neighbour list names, where it is first named. Nodes are compared by identity
|
|
16
|
+
* (`Map` semantics, so `NaN` equals `NaN`); `neighboursOf` is called once per
|
|
17
|
+
* node, its iterable read once.
|
|
18
|
+
*
|
|
19
|
+
* Time complexity: O((V + E) · α(V)), effectively linear. Memory: O(V).
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* const graph = new Graph<string>();
|
|
24
|
+
* // …
|
|
25
|
+
* connectedComponents(graph.nodes(), (node) => graph.neighbors(node));
|
|
26
|
+
* ```;
|
|
27
|
+
*
|
|
28
|
+
* @param nodes - The nodes of the graph; a repeated one counts once. A node
|
|
29
|
+
* left out is still found when a neighbour list names it.
|
|
30
|
+
* @param neighboursOf - The neighbours of a node, or `undefined` for none.
|
|
31
|
+
* @returns The components, each a fresh array of its nodes.
|
|
32
|
+
* @throws Whatever `neighboursOf` or an iterator throws.
|
|
33
|
+
*/
|
|
34
|
+
export function connectedComponents(nodes, neighboursOf) {
|
|
35
|
+
const sets = new StaticDisjointSet();
|
|
36
|
+
const order = [];
|
|
37
|
+
const reach = (node) => {
|
|
38
|
+
if (!sets.has(node)) {
|
|
39
|
+
sets.makeSet(node);
|
|
40
|
+
order.push(node);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
for (const node of nodes) {
|
|
44
|
+
reach(node);
|
|
45
|
+
}
|
|
46
|
+
// `order` grows while it is walked, so a node only a neighbour list names is
|
|
47
|
+
// expanded in turn.
|
|
48
|
+
for (let index = 0; index < order.length; index++) {
|
|
49
|
+
const node = order[index];
|
|
50
|
+
const neighbours = neighboursOf(node);
|
|
51
|
+
if (neighbours === undefined) {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
for (const neighbour of neighbours) {
|
|
55
|
+
reach(neighbour);
|
|
56
|
+
sets.union(node, neighbour);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const components = new Map();
|
|
60
|
+
const result = [];
|
|
61
|
+
for (const node of order) {
|
|
62
|
+
const root = sets.find(node);
|
|
63
|
+
const component = components.get(root);
|
|
64
|
+
if (component === undefined) {
|
|
65
|
+
const created = [node];
|
|
66
|
+
components.set(root, created);
|
|
67
|
+
result.push(created);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
component.push(node);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=connected-components.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connected-components.js","sourceRoot":"","sources":["../../src/graph/connected-components.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,UAAU,mBAAmB,CAClC,KAAsB,EACtB,YAA0D;IAE1D,MAAM,IAAI,GAAG,IA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C;YACvB,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAC9B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtB,CAAC;aAAM,CAAC;YACP,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export type FloydWarshallTraits<TNode> = {
|
|
2
|
+
/** The successors of a node, or `undefined` for none; each must be in `nodes`. */
|
|
3
|
+
neighboursOf: (node: TNode) => Iterable<TNode> | undefined;
|
|
4
|
+
/**
|
|
5
|
+
* Cost of the edge from `from` to `to`, any number but `NaN`; negative costs
|
|
6
|
+
* are allowed as long as no cycle is negative. Defaults to `1`, which makes
|
|
7
|
+
* distance equal hop count. Called once per edge read; of parallel edges the
|
|
8
|
+
* cheapest counts.
|
|
9
|
+
*/
|
|
10
|
+
costOf?: (from: TNode, to: TNode) => number;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Shortest distances between every pair of nodes, as flat `n × n` row-major
|
|
14
|
+
* tables indexed by position in {@link AllPairsShortestPaths.nodes}: the entry
|
|
15
|
+
* for the pair `(i, j)` is at `i · n + j`.
|
|
16
|
+
*/
|
|
17
|
+
export type AllPairsShortestPaths<TNode> = {
|
|
18
|
+
/** The nodes, in the order given, which numbers the rows and columns. */
|
|
19
|
+
readonly nodes: readonly TNode[];
|
|
20
|
+
/** Cost of a shortest path from row to column; `Infinity` when unreachable. */
|
|
21
|
+
readonly distances: Float64Array;
|
|
22
|
+
/**
|
|
23
|
+
* Position of the node after the row's on a shortest path to the column: the
|
|
24
|
+
* column itself for a direct edge, the row itself on the diagonal, `-1` when
|
|
25
|
+
* the column is unreachable. Following it from `i` until `j` gives the path.
|
|
26
|
+
*/
|
|
27
|
+
readonly nextHops: Int32Array;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Shortest paths between every pair of nodes of a dense directed graph — the
|
|
31
|
+
* question `aStar` answers one pair at a time, and the base of a diameter, an
|
|
32
|
+
* eccentricity or a transitive closure. For an undirected graph, list each edge
|
|
33
|
+
* from both ends.
|
|
34
|
+
*
|
|
35
|
+
* Floyd–Warshall: every node in turn is allowed as an intermediate stop, so it
|
|
36
|
+
* handles negative edge costs and reports a negative cycle rather than
|
|
37
|
+
* returning distances that do not exist. Three nested loops, no recursion and
|
|
38
|
+
* no allocation beyond the result.
|
|
39
|
+
*
|
|
40
|
+
* Nodes are compared by identity (`Map` semantics, so `NaN` equals `NaN`).
|
|
41
|
+
* `neighboursOf` is called once per node.
|
|
42
|
+
*
|
|
43
|
+
* Time complexity: O(V³ + E). Memory: O(V²), the result.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* const { nodes, distances, nextHops } = floydWarshall(cities, {
|
|
48
|
+
* neighboursOf: (city) => roads.outNeighbors(city),
|
|
49
|
+
* costOf: (from, to) => roads.edgeLabel(from, to)!,
|
|
50
|
+
* });
|
|
51
|
+
* // The path from nodes[i] to nodes[j], when distances[i * n + j] is finite.
|
|
52
|
+
* const path = [nodes[i]];
|
|
53
|
+
* for (let at = i; at !== j; ) {
|
|
54
|
+
* at = nextHops[at * nodes.length + j];
|
|
55
|
+
* path.push(nodes[at]);
|
|
56
|
+
* }
|
|
57
|
+
* ```;
|
|
58
|
+
*
|
|
59
|
+
* @param nodes - The nodes of the graph, each once.
|
|
60
|
+
* @param traits - How to expand and weight a node.
|
|
61
|
+
* @returns The distance and next-hop tables.
|
|
62
|
+
* @throws {RangeError} When a node is repeated in `nodes`, a neighbour is not
|
|
63
|
+
* in `nodes`, a cost is `NaN`, or a cycle has a negative total cost.
|
|
64
|
+
* @throws Whatever `neighboursOf`, `costOf` or an iterator throws.
|
|
65
|
+
*/
|
|
66
|
+
export declare function floydWarshall<TNode>(nodes: Iterable<TNode>, traits: FloydWarshallTraits<TNode>): AllPairsShortestPaths<TNode>;
|
|
67
|
+
//# sourceMappingURL=floyd-warshall.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"floyd-warshall.d.ts","sourceRoot":"","sources":["../../src/graph/floyd-warshall.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,mBAAmB,CAAC,KAAK,IAAI;IACxC,kFAAkF;IAClF,YAAY,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,QAAQ,CAAC,KAAK,CAAC,GAAG,SAAS,CAAC;IAE3D;;;;;OAKG;IACH,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,KAAK,MAAM,CAAC;CAC5C,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,CAAC,KAAK,IAAI;IAC1C,yEAAyE;IACzE,QAAQ,CAAC,KAAK,EAAE,SAAS,KAAK,EAAE,CAAC;IAEjC,+EAA+E;IAC/E,QAAQ,CAAC,SAAS,EAAE,YAAY,CAAC;IAEjC;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;CAC9B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAClC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,EACtB,MAAM,EAAE,mBAAmB,CAAC,KAAK,CAAC,GAChC,qBAAqB,CAAC,KAAK,CAAC,CA+E9B"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { describeValue } from "@ac-kit/core";
|
|
2
|
+
/**
|
|
3
|
+
* Shortest paths between every pair of nodes of a dense directed graph — the
|
|
4
|
+
* question `aStar` answers one pair at a time, and the base of a diameter, an
|
|
5
|
+
* eccentricity or a transitive closure. For an undirected graph, list each edge
|
|
6
|
+
* from both ends.
|
|
7
|
+
*
|
|
8
|
+
* Floyd–Warshall: every node in turn is allowed as an intermediate stop, so it
|
|
9
|
+
* handles negative edge costs and reports a negative cycle rather than
|
|
10
|
+
* returning distances that do not exist. Three nested loops, no recursion and
|
|
11
|
+
* no allocation beyond the result.
|
|
12
|
+
*
|
|
13
|
+
* Nodes are compared by identity (`Map` semantics, so `NaN` equals `NaN`).
|
|
14
|
+
* `neighboursOf` is called once per node.
|
|
15
|
+
*
|
|
16
|
+
* Time complexity: O(V³ + E). Memory: O(V²), the result.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* const { nodes, distances, nextHops } = floydWarshall(cities, {
|
|
21
|
+
* neighboursOf: (city) => roads.outNeighbors(city),
|
|
22
|
+
* costOf: (from, to) => roads.edgeLabel(from, to)!,
|
|
23
|
+
* });
|
|
24
|
+
* // The path from nodes[i] to nodes[j], when distances[i * n + j] is finite.
|
|
25
|
+
* const path = [nodes[i]];
|
|
26
|
+
* for (let at = i; at !== j; ) {
|
|
27
|
+
* at = nextHops[at * nodes.length + j];
|
|
28
|
+
* path.push(nodes[at]);
|
|
29
|
+
* }
|
|
30
|
+
* ```;
|
|
31
|
+
*
|
|
32
|
+
* @param nodes - The nodes of the graph, each once.
|
|
33
|
+
* @param traits - How to expand and weight a node.
|
|
34
|
+
* @returns The distance and next-hop tables.
|
|
35
|
+
* @throws {RangeError} When a node is repeated in `nodes`, a neighbour is not
|
|
36
|
+
* in `nodes`, a cost is `NaN`, or a cycle has a negative total cost.
|
|
37
|
+
* @throws Whatever `neighboursOf`, `costOf` or an iterator throws.
|
|
38
|
+
*/
|
|
39
|
+
export function floydWarshall(nodes, traits) {
|
|
40
|
+
const { neighboursOf, costOf } = traits;
|
|
41
|
+
const nodeList = [...nodes];
|
|
42
|
+
const n = nodeList.length;
|
|
43
|
+
const indices = new Map();
|
|
44
|
+
for (let index = 0; index < n; index++) {
|
|
45
|
+
const node = nodeList[index];
|
|
46
|
+
if (indices.has(node)) {
|
|
47
|
+
throw new RangeError(`floydWarshall: nodes[${index}] repeats nodes[${indices.get(node)}]`);
|
|
48
|
+
}
|
|
49
|
+
indices.set(node, index);
|
|
50
|
+
}
|
|
51
|
+
const distances = new Float64Array(n * n).fill(Infinity);
|
|
52
|
+
const nextHops = new Int32Array(n * n).fill(-1);
|
|
53
|
+
for (let row = 0; row < n; row++) {
|
|
54
|
+
distances[row * n + row] = 0;
|
|
55
|
+
nextHops[row * n + row] = row;
|
|
56
|
+
}
|
|
57
|
+
for (let row = 0; row < n; row++) {
|
|
58
|
+
const from = nodeList[row];
|
|
59
|
+
const neighbours = neighboursOf(from);
|
|
60
|
+
if (neighbours === undefined) {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
for (const to of neighbours) {
|
|
64
|
+
const column = indices.get(to);
|
|
65
|
+
if (column === undefined) {
|
|
66
|
+
throw new RangeError(`floydWarshall: a neighbour of nodes[${row}], ${describeValue(to)}, is not in nodes`);
|
|
67
|
+
}
|
|
68
|
+
const cost = costOf === undefined ? 1 : costOf(from, to);
|
|
69
|
+
if (cost !== cost) {
|
|
70
|
+
throw new RangeError(`floydWarshall: the cost from nodes[${row}] to nodes[${column}] is NaN`);
|
|
71
|
+
}
|
|
72
|
+
const cell = row * n + column;
|
|
73
|
+
if (cost < distances[cell]) {
|
|
74
|
+
distances[cell] = cost;
|
|
75
|
+
nextHops[cell] = column;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (let via = 0; via < n; via++) {
|
|
80
|
+
const viaRow = via * n;
|
|
81
|
+
for (let row = 0; row < n; row++) {
|
|
82
|
+
const rowStart = row * n;
|
|
83
|
+
const toVia = distances[rowStart + via];
|
|
84
|
+
if (toVia === Infinity) {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const hopToVia = nextHops[rowStart + via];
|
|
88
|
+
for (let column = 0; column < n; column++) {
|
|
89
|
+
// `Infinity + x` never compares below, and `-Infinity + Infinity`
|
|
90
|
+
// is `NaN`, which never does either.
|
|
91
|
+
const through = toVia + distances[viaRow + column];
|
|
92
|
+
if (through < distances[rowStart + column]) {
|
|
93
|
+
distances[rowStart + column] = through;
|
|
94
|
+
nextHops[rowStart + column] = hopToVia;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
for (let row = 0; row < n; row++) {
|
|
100
|
+
if (distances[row * n + row] < 0) {
|
|
101
|
+
throw new RangeError(`floydWarshall: a cycle through nodes[${row}] has a negative cost`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return { nodes: nodeList, distances, nextHops };
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=floyd-warshall.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"floyd-warshall.js","sourceRoot":"","sources":["../../src/graph/floyd-warshall.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAmC7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,MAAM,UAAU,aAAa,CAC5B,KAAsB,EACtB,MAAkC;IAElC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;IACxC,MAAM,QAAQ,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC;IAC5B,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC;IAC1B,MAAM,OAAO,GAAG,IAAI,GAAG,EAAiB,CAAC;IACzC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QACxC,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAE,CAAC;QAC9B,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YACvB,MAAM,IAAI,UAAU,CACnB,wBAAwB,KAAK,mBAAmB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAE,GAAG,CACrE,CAAC;QACH,CAAC;QACD,OAAO,CAAC,G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AC;QACF,CAAC;IACF,CAAC;IAED,KAAK,IAAI,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,EAAE,EAAE,CAAC;QAClC,IAAI,SAAS,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAE,GAAG,CAAC,EAAE,CAAC;YACnC,MAAM,IAAI,UAAU,CACnB,wCAAwC,GAAG,uBAAuB,CAClE,CAAC;QACH,CAAC;IACF,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC;AACjD,CAAC"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error thrown by a graph algorithm that needs an acyclic graph and was given a
|
|
3
|
+
* cycle, carrying one offending cycle so the message shown to a user can name
|
|
4
|
+
* it ("a imports b imports a").
|
|
5
|
+
*
|
|
6
|
+
* @template TNode The graph's node type.
|
|
7
|
+
*/
|
|
8
|
+
export declare class GraphCycleError<TNode = unknown> extends Error {
|
|
9
|
+
/**
|
|
10
|
+
* The nodes of one cycle in edge order: each one has an edge to the next, and
|
|
11
|
+
* the last one to the first (a self-loop is a single node).
|
|
12
|
+
*/
|
|
13
|
+
readonly cycle: readonly TNode[];
|
|
14
|
+
constructor(functionName: string, cycle: readonly TNode[]);
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=graph-cycle-error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph-cycle-error.d.ts","sourceRoot":"","sources":["../../src/graph/graph-cycle-error.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,qBAAa,eAAe,CAAC,KAAK,GAAG,OAAO,CAAE,SAAQ,KAAK;IAC1D;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,SAAS,KAAK,EAAE,CAAC;IAEjC,YAAY,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,KAAK,EAAE,EAMxD;CACD"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error thrown by a graph algorithm that needs an acyclic graph and was given a
|
|
3
|
+
* cycle, carrying one offending cycle so the message shown to a user can name
|
|
4
|
+
* it ("a imports b imports a").
|
|
5
|
+
*
|
|
6
|
+
* @template TNode The graph's node type.
|
|
7
|
+
*/
|
|
8
|
+
export class GraphCycleError extends Error {
|
|
9
|
+
/**
|
|
10
|
+
* The nodes of one cycle in edge order: each one has an edge to the next, and
|
|
11
|
+
* the last one to the first (a self-loop is a single node).
|
|
12
|
+
*/
|
|
13
|
+
cycle;
|
|
14
|
+
constructor(functionName, cycle) {
|
|
15
|
+
super(`${functionName}: the graph has a cycle through ${cycle.length} node${cycle.length === 1 ? "" : "s"}`);
|
|
16
|
+
this.name = "GraphCycleError";
|
|
17
|
+
this.cycle = cycle;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=graph-cycle-error.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph-cycle-error.js","sourceRoot":"","sources":["../../src/graph/graph-cycle-error.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,OAAO,eAAiC,SAAQ,KAAK;IAC1D;;;OAGG;IACM,KAAK,CAAmB;IAEjC,YAAY,YAAoB,EAAE,KAAuB;QACxD,KAAK,CACJ,GAAG,YAAY,mCAAmC,KAAK,CAAC,MAAM,QAAQ,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CACrG,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACpB,CAAC;CACD"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { DefinedValue } from "@ac-kit/core";
|
|
2
|
+
/**
|
|
3
|
+
* The deepest node that is an ancestor of both `a` and `b` — where two paths
|
|
4
|
+
* through a tree diverged: the closest shared directory of two files, the merge
|
|
5
|
+
* base of two commits in a linear history, the innermost scope holding two
|
|
6
|
+
* declarations. A node counts as its own ancestor, so when `a` is an ancestor
|
|
7
|
+
* of `b`, the answer is `a`.
|
|
8
|
+
*
|
|
9
|
+
* Walks up from `a` marking every ancestor, then up from `b` until a marked
|
|
10
|
+
* one, so it needs only `parentOf` and no preprocessing; for many queries over
|
|
11
|
+
* one fixed tree, an Euler-tour or binary-lifting index answers each in O(1) or
|
|
12
|
+
* O(log h) instead. Iterative, so a deep tree cannot overflow the stack. Nodes
|
|
13
|
+
* are compared by identity (`Set` semantics, so `NaN` equals `NaN`).
|
|
14
|
+
*
|
|
15
|
+
* Time complexity: O(dₐ + d_b), the depths of the two nodes. Memory: the same.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* const parents = new Map([["b", "a"], ["c", "a"], ["d", "b"]]);
|
|
20
|
+
* lowestCommonAncestor("d", "c", (node) => parents.get(node)); // "a"
|
|
21
|
+
* ```;
|
|
22
|
+
*
|
|
23
|
+
* @param a - One node.
|
|
24
|
+
* @param b - The other node.
|
|
25
|
+
* @param parentOf - The parent of a node, or `undefined` for a root.
|
|
26
|
+
* @returns The lowest common ancestor, or `undefined` when the two nodes have
|
|
27
|
+
* none (they sit in different trees).
|
|
28
|
+
* @throws {RangeError} When following `parentOf` from `a` or from `b` comes
|
|
29
|
+
* back to a node already passed: the parents form a cycle, not a tree.
|
|
30
|
+
*/
|
|
31
|
+
export declare function lowestCommonAncestor<TNode extends DefinedValue>(a: TNode, b: TNode, parentOf: (node: TNode) => TNode | undefined): TNode | undefined;
|
|
32
|
+
//# sourceMappingURL=lowest-common-ancestor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lowest-common-ancestor.d.ts","sourceRoot":"","sources":["../../src/graph/lowest-common-ancestor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,SAAS,YAAY,EAC9D,CAAC,EAAE,KAAK,EACR,CAAC,EAAE,KAAK,EACR,QAAQ,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,KAAK,GAAG,SAAS,GAC1C,KAAK,GAAG,SAAS,CA+BnB"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The deepest node that is an ancestor of both `a` and `b` — where two paths
|
|
3
|
+
* through a tree diverged: the closest shared directory of two files, the merge
|
|
4
|
+
* base of two commits in a linear history, the innermost scope holding two
|
|
5
|
+
* declarations. A node counts as its own ancestor, so when `a` is an ancestor
|
|
6
|
+
* of `b`, the answer is `a`.
|
|
7
|
+
*
|
|
8
|
+
* Walks up from `a` marking every ancestor, then up from `b` until a marked
|
|
9
|
+
* one, so it needs only `parentOf` and no preprocessing; for many queries over
|
|
10
|
+
* one fixed tree, an Euler-tour or binary-lifting index answers each in O(1) or
|
|
11
|
+
* O(log h) instead. Iterative, so a deep tree cannot overflow the stack. Nodes
|
|
12
|
+
* are compared by identity (`Set` semantics, so `NaN` equals `NaN`).
|
|
13
|
+
*
|
|
14
|
+
* Time complexity: O(dₐ + d_b), the depths of the two nodes. Memory: the same.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const parents = new Map([["b", "a"], ["c", "a"], ["d", "b"]]);
|
|
19
|
+
* lowestCommonAncestor("d", "c", (node) => parents.get(node)); // "a"
|
|
20
|
+
* ```;
|
|
21
|
+
*
|
|
22
|
+
* @param a - One node.
|
|
23
|
+
* @param b - The other node.
|
|
24
|
+
* @param parentOf - The parent of a node, or `undefined` for a root.
|
|
25
|
+
* @returns The lowest common ancestor, or `undefined` when the two nodes have
|
|
26
|
+
* none (they sit in different trees).
|
|
27
|
+
* @throws {RangeError} When following `parentOf` from `a` or from `b` comes
|
|
28
|
+
* back to a node already passed: the parents form a cycle, not a tree.
|
|
29
|
+
*/
|
|
30
|
+
export function lowestCommonAncestor(a, b, parentOf) {
|
|
31
|
+
const ancestorsOfA = new Set();
|
|
32
|
+
for (let node = a; node !== undefined; node = parentOf(node)) {
|
|
33
|
+
if (ancestorsOfA.has(node)) {
|
|
34
|
+
throw cycleError_("a");
|
|
35
|
+
}
|
|
36
|
+
ancestorsOfA.add(node);
|
|
37
|
+
}
|
|
38
|
+
// Created on the first step off `a`'s line, so a query whose `b` lies on it
|
|
39
|
+
// allocates one set only.
|
|
40
|
+
let ancestorsOfB;
|
|
41
|
+
for (let node = b; node !== undefined; node = parentOf(node)) {
|
|
42
|
+
if (ancestorsOfA.has(node)) {
|
|
43
|
+
return node;
|
|
44
|
+
}
|
|
45
|
+
ancestorsOfB ??= new Set();
|
|
46
|
+
if (ancestorsOfB.has(node)) {
|
|
47
|
+
throw cycleError_("b");
|
|
48
|
+
}
|
|
49
|
+
ancestorsOfB.add(node);
|
|
50
|
+
}
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
function cycleError_(from) {
|
|
54
|
+
return new RangeError(`lowestCommonAncestor: the parents of ${from} form a cycle`);
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=lowest-common-ancestor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lowest-common-ancestor.js","sourceRoot":"","sources":["../../src/graph/lowest-common-ancestor.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,UAAU,oBAAoB,CACnC,CAAQ,EACR,CAAQ,EACR,QAA4C;IAE5C,MAAM,YAAY,GAAG,IAAI,GAAG,EAAS,CAAC;IACtC,KACC,IAAI,IAAI,GAAsB,CAAC,EAC/B,IAAI,KAAK,SAAS,EAClB,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,EACpB,CAAC;QACF,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5B,MAAM,WAAW,CAAC,GAAG,CAAC,CAAC;QACxB,CAAC;QACD,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IAED,4EAA4E;IAC5E,0BAA0B;IAC1B,IAAI,YAAoC,CAAC;IACzC,KACC,IAAI,IAAI,GAAsB,CAAC,EAC/B,IAAI,KAAK,SAAS,EAClB,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,EACpB,CAAC;QACF,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5B,OAAO,IAAI,CAAC;QACb,CAAC;QACD,YAAY,KAAK,IAAI,GAAG,EAAE,CAAC;QAC3B,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5B,MAAM,WAAW,CAAC,GAAG,CAAC,CAAC;QACxB,CAAC;QACD,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,SAAS,WAAW,CAAC,IAAY;IAChC,OAAO,IAAI,UAAU,CACpB,wCAAwC,IAAI,eAAe,CAC3D,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { WorkBudget } from "@ac-kit/core";
|
|
2
|
+
export type TopologicalSortOptions = {
|
|
3
|
+
/**
|
|
4
|
+
* Charged 1 for each root read (a repeated one included), 1 for each node
|
|
5
|
+
* reached and 1 for each successor read (each edge, repeated ones included),
|
|
6
|
+
* so a sort over an untrusted graph or an endless roots iterable can be
|
|
7
|
+
* capped. Whatever `spend` throws propagates unchanged.
|
|
8
|
+
*/
|
|
9
|
+
budget?: WorkBudget;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Orders every node reachable from `roots` so that each node comes before all
|
|
13
|
+
* of its successors: the dependency order of a directed acyclic graph, for a
|
|
14
|
+
* build order, a task scheduler or module initialisation. With `childrenOf`
|
|
15
|
+
* returning a node's _dependencies_ rather than its dependents, reverse the
|
|
16
|
+
* result to list dependencies first.
|
|
17
|
+
*
|
|
18
|
+
* Kahn's algorithm: nodes with no remaining predecessor are emitted in the
|
|
19
|
+
* order they were first reached, then each emitted node releases its
|
|
20
|
+
* successors. So the order is deterministic, and nodes with no edge between
|
|
21
|
+
* them keep the order `roots` and `childrenOf` gave them. Iterative throughout,
|
|
22
|
+
* so a hostile deep graph cannot overflow the stack.
|
|
23
|
+
*
|
|
24
|
+
* Nodes are compared by identity (`Map` semantics, so `NaN` equals `NaN`).
|
|
25
|
+
* `childrenOf` is called once per node, and the iterable it returns is read
|
|
26
|
+
* once; parallel edges are allowed. A cycle is never answered with a partial
|
|
27
|
+
* order: a {@link GraphCycleError} names one.
|
|
28
|
+
*
|
|
29
|
+
* Time complexity: O(V + E) for the nodes and edges reached. Memory: O(V + E).
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* const dependents = new Map([
|
|
34
|
+
* ["core", ["data", "algo"]],
|
|
35
|
+
* ["data", ["algo"]],
|
|
36
|
+
* ]);
|
|
37
|
+
* topologicalSort(["core"], (name) => dependents.get(name));
|
|
38
|
+
* // ["core", "data", "algo"]
|
|
39
|
+
* ```;
|
|
40
|
+
*
|
|
41
|
+
* @param roots - Where to start; a root reached from an earlier one is not
|
|
42
|
+
* reached again. Pass every node to order a whole graph.
|
|
43
|
+
* @param childrenOf - The successors of a node, or `undefined` for none.
|
|
44
|
+
* @param options - A work budget.
|
|
45
|
+
* @returns Every reachable node once, each before its successors.
|
|
46
|
+
* @throws {GraphCycleError} When a cycle is reachable; its `cycle` lists one,
|
|
47
|
+
* in edge order.
|
|
48
|
+
* @throws Whatever `options.budget.spend`, `childrenOf` or an iterator throws.
|
|
49
|
+
*/
|
|
50
|
+
export declare function topologicalSort<TNode>(roots: Iterable<TNode>, childrenOf: (node: TNode) => Iterable<TNode> | undefined, options?: TopologicalSortOptions): TNode[];
|
|
51
|
+
//# sourceMappingURL=topological-sort.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"topological-sort.d.ts","sourceRoot":"","sources":["../../src/graph/topological-sort.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAK/C,MAAM,MAAM,sBAAsB,GAAG;IACpC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,UAAU,CAAC;CACpB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAgB,eAAe,CAAC,KAAK,EACpC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,EACtB,UAAU,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,QAAQ,CAAC,KAAK,CAAC,GAAG,SAAS,EACxD,OAAO,GAAE,sBAA2B,GAClC,KAAK,EAAE,CA6ET"}
|