@ac-kit/algo 0.2.4 → 0.3.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 CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - c18e8f3: `viterbi`, the cheapest path through a layered state space whose equal states
8
+ merge, with an optional beam; and `combinations` / `combinationsLazy`, every
9
+ `k`-subset of a list.
10
+
3
11
  ## 0.2.4
4
12
 
5
13
  ### Patch Changes
package/README.md CHANGED
@@ -30,7 +30,8 @@ const distinct = [...uniqBy(events, (event) => event.correlationId)];
30
30
  (which is Dijkstra's algorithm when you give it no heuristic) and greedy
31
31
  `bestFirstSearch`, all over a `childrenOf`/`neighboursOf` callback rather than
32
32
  any particular graph type.
33
- - **State-space search** — `beamSearch` for a width-bounded exploration, and
33
+ - **State-space search** — `beamSearch` for a width-bounded exploration,
34
+ `viterbi` for the cheapest path through layers whose equal states merge, and
34
35
  `backtrack` for constraint search that undoes its own moves on the way back
35
36
  out of a dead end.
36
37
  - **Binary search** — `bisect`, `bisectLeft`, `bisectRight`, `bisectCenter` and
@@ -39,6 +40,8 @@ const distinct = [...uniqBy(events, (event) => event.correlationId)];
39
40
  - **Selection** — `quickselect` for order statistics, `minBy`/`maxBy` for the
40
41
  extreme item by a derived key, `selectAt` for picking positions.
41
42
  - **Sorting** — `radixSort`, a stable, comparator-free sort over an integer key.
43
+ - **Combinatorics** — `combinations` and `combinationsLazy`, every `k`-subset
44
+ of your items.
42
45
  - **Grouping** — `groupBy` (nesting one `Map` level per accessor), `partition`,
43
46
  `partitionIndices`, `uniq` and `uniqBy`.
44
47
  - **Set algebra** — `union`, `intersection`, `difference`,
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Every `k`-element subset of `items`, each in the order its elements appear in
3
+ * `items`, the subsets in lexicographic order of their positions — the eager
4
+ * form of {@link combinationsLazy}.
5
+ *
6
+ * Reach for it to try every way of choosing `k` of a small set, such as fingers
7
+ * for a chord. Use {@link combinationsLazy} when the subsets are many and are
8
+ * consumed one by one.
9
+ *
10
+ * Empty when `k` is negative, not an integer, or above `items.length`; one
11
+ * empty subset when `k` is 0.
12
+ *
13
+ * Time complexity: O(C(n, k) · k) for `n = items.length`. Memory: the same, for
14
+ * the result.
15
+ *
16
+ * @example
17
+ * combinations(["a", "b", "c"], 2); // [["a", "b"], ["a", "c"], ["b", "c"]]
18
+ */
19
+ export declare function combinations<T>(items: readonly T[], k: number): T[][];
20
+ /**
21
+ * Every `k`-element subset of `items`, yielded one at a time in the order of
22
+ * {@link combinations}. Each yielded array is fresh and owned by the caller.
23
+ *
24
+ * Time complexity: O(k) per subset. Memory: O(k).
25
+ *
26
+ * @example
27
+ * [...combinationsLazy([1, 2, 3], 2)]; // [[1, 2], [1, 3], [2, 3]]
28
+ */
29
+ export declare function combinationsLazy<T>(items: readonly T[], k: number): IterableIterator<T[]>;
30
+ //# sourceMappingURL=combinations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"combinations.d.ts","sourceRoot":"","sources":["../../src/combinatorics/combinations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,CAAC,EAAE,EAAE,CAErE;AAED;;;;;;;;GAQG;AACH,wBAAiB,gBAAgB,CAAC,CAAC,EAClC,KAAK,EAAE,SAAS,CAAC,EAAE,EACnB,CAAC,EAAE,MAAM,GACP,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAuBvB"}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Every `k`-element subset of `items`, each in the order its elements appear in
3
+ * `items`, the subsets in lexicographic order of their positions — the eager
4
+ * form of {@link combinationsLazy}.
5
+ *
6
+ * Reach for it to try every way of choosing `k` of a small set, such as fingers
7
+ * for a chord. Use {@link combinationsLazy} when the subsets are many and are
8
+ * consumed one by one.
9
+ *
10
+ * Empty when `k` is negative, not an integer, or above `items.length`; one
11
+ * empty subset when `k` is 0.
12
+ *
13
+ * Time complexity: O(C(n, k) · k) for `n = items.length`. Memory: the same, for
14
+ * the result.
15
+ *
16
+ * @example
17
+ * combinations(["a", "b", "c"], 2); // [["a", "b"], ["a", "c"], ["b", "c"]]
18
+ */
19
+ export function combinations(items, k) {
20
+ return [...combinationsLazy(items, k)];
21
+ }
22
+ /**
23
+ * Every `k`-element subset of `items`, yielded one at a time in the order of
24
+ * {@link combinations}. Each yielded array is fresh and owned by the caller.
25
+ *
26
+ * Time complexity: O(k) per subset. Memory: O(k).
27
+ *
28
+ * @example
29
+ * [...combinationsLazy([1, 2, 3], 2)]; // [[1, 2], [1, 3], [2, 3]]
30
+ */
31
+ export function* combinationsLazy(items, k) {
32
+ const n = items.length;
33
+ if (!Number.isInteger(k) || k < 0 || k > n) {
34
+ return;
35
+ }
36
+ const positions = Array.from({ length: k }, (_, index) => index);
37
+ while (true) {
38
+ yield positions.map((position) => items[position]);
39
+ // The rightmost position that can still move right, then reset those after it.
40
+ let index = k - 1;
41
+ while (index >= 0 && positions[index] === n - k + index) {
42
+ index--;
43
+ }
44
+ if (index < 0) {
45
+ return;
46
+ }
47
+ positions[index]++;
48
+ for (let next = index + 1; next < k; next++) {
49
+ positions[next] = positions[next - 1] + 1;
50
+ }
51
+ }
52
+ }
53
+ //# sourceMappingURL=combinations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"combinations.js","sourceRoot":"","sources":["../../src/combinatorics/combinations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,YAAY,CAAI,KAAmB,EAAE,CAAS;IAC7D,OAAO,CAAC,GAAG,gBAAgB,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;AACxC,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,SAAS,CAAC,CAAC,gBAAgB,CAChC,KAAmB,EACnB,CAAS;IAET,MAAM,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC;IACvB,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QAC5C,OAAO;IACR,CAAC;IAED,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC;IACjE,OAAO,IAAI,EAAE,CAAC;QACb,MAAM,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAE,CAAC,CAAC;QAEpD,+EAA+E;QAC/E,IAAI,KAAK,GAAG,CAAC,GAAG,CAAC,CAAC;QAClB,OAAO,KAAK,IAAI,CAAC,IAAI,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,EAAE,CAAC;YACzD,KAAK,EAAE,CAAC;QACT,CAAC;QACD,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YACf,OAAO;QACR,CAAC;QACD,SAAS,CAAC,KAAK,CAAE,EAAE,CAAC;QACpB,KAAK,IAAI,IAAI,GAAG,KAAK,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC;YAC7C,SAAS,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,IAAI,GAAG,CAAC,CAAE,GAAG,CAAC,CAAC;QAC5C,CAAC;IACF,CAAC;AACF,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./combinatorics/combinations.js";
1
2
  export * from "./distribute/spread-evenly.js";
2
3
  export * from "./graph/a-star.js";
3
4
  export * from "./graph/best-first-search.js";
@@ -13,6 +14,7 @@ export * from "./interval/merge-intervals.js";
13
14
  export * from "./interval/subtract-intervals.js";
14
15
  export * from "./optimize/backtrack.js";
15
16
  export * from "./optimize/beam-search.js";
17
+ export * from "./optimize/viterbi.js";
16
18
  export * from "./ordered/bisect-center.js";
17
19
  export * from "./ordered/bisect-left.js";
18
20
  export * from "./ordered/bisect-right.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,mBAAmB,CAAC;AAClC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,sBAAsB,CAAC;AACrC,cAAc,oCAAoC,CAAC;AACnD,cAAc,mCAAmC,CAAC;AAClD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sCAAsC,CAAC;AACrD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,kCAAkC,CAAC;AACjD,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,qBAAqB,CAAC;AACpC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iCAAiC,CAAC;AAChD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,mBAAmB,CAAC;AAClC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,sBAAsB,CAAC;AACrC,cAAc,oCAAoC,CAAC;AACnD,cAAc,mCAAmC,CAAC;AAClD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sCAAsC,CAAC;AACrD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,kCAAkC,CAAC;AACjD,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,qBAAqB,CAAC;AACpC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC"}
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./combinatorics/combinations.js";
1
2
  export * from "./distribute/spread-evenly.js";
2
3
  export * from "./graph/a-star.js";
3
4
  export * from "./graph/best-first-search.js";
@@ -13,6 +14,7 @@ export * from "./interval/merge-intervals.js";
13
14
  export * from "./interval/subtract-intervals.js";
14
15
  export * from "./optimize/backtrack.js";
15
16
  export * from "./optimize/beam-search.js";
17
+ export * from "./optimize/viterbi.js";
16
18
  export * from "./ordered/bisect-center.js";
17
19
  export * from "./ordered/bisect-left.js";
18
20
  export * from "./ordered/bisect-right.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,mBAAmB,CAAC;AAClC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,sBAAsB,CAAC;AACrC,cAAc,oCAAoC,CAAC;AACnD,cAAc,mCAAmC,CAAC;AAClD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sCAAsC,CAAC;AACrD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,kCAAkC,CAAC;AACjD,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,qBAAqB,CAAC;AACpC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iCAAiC,CAAC;AAChD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,mBAAmB,CAAC;AAClC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,sBAAsB,CAAC;AACrC,cAAc,oCAAoC,CAAC;AACnD,cAAc,mCAAmC,CAAC;AAClD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sCAAsC,CAAC;AACrD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,kCAAkC,CAAC;AACjD,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,qBAAqB,CAAC;AACpC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC"}
@@ -0,0 +1,79 @@
1
+ import type { DefinedValue } from "@ac-kit/core";
2
+ /** A successor of a state, with the cost of moving to it. */
3
+ export type ViterbiSuccessor<TState> = {
4
+ state: TState;
5
+ /** The transition's cost. **Lower is better**; never negative. */
6
+ cost: number;
7
+ };
8
+ /** How a caller's layered state space is expanded and recombined. */
9
+ export type ViterbiTraits<TState> = {
10
+ /**
11
+ * The states reachable from `state` in layer `layer` (0 for the first layer
12
+ * after the initial state), each with its transition cost. Return `[]` for a
13
+ * dead end.
14
+ */
15
+ nextStatesOf(state: TState, layer: number): readonly ViterbiSuccessor<TState>[];
16
+ /**
17
+ * Identifies a state: two states of one layer with the same key are the same
18
+ * state, and only the cheaper path to it is kept.
19
+ */
20
+ keyOf(state: TState): string | number;
21
+ };
22
+ export type ViterbiOptions = {
23
+ /**
24
+ * The most states kept per layer, the cheapest first. Unbounded by default,
25
+ * which makes the search exact; a bound makes it a beam search over the
26
+ * recombined states, `O(beamWidth)` states per layer.
27
+ */
28
+ beamWidth?: number;
29
+ };
30
+ /** The cheapest path found, one state per layer. */
31
+ export type ViterbiPath<TState> = {
32
+ /** The state chosen in each layer, `layerCount` of them. */
33
+ states: TState[];
34
+ /** The sum of the path's transition costs. */
35
+ cost: number;
36
+ };
37
+ /**
38
+ * The cheapest path through a layered state space: from `initialState`, one
39
+ * state per layer, minimising the summed transition cost.
40
+ *
41
+ * Reach for it when a sequence of decisions is scored step by step and many
42
+ * different histories end in the same state — decoding a hidden Markov model,
43
+ * fingering a passage chord by chord, assigning each item of a sequence a
44
+ * label. States with equal `keyOf` merge on the cheaper path, which is what
45
+ * keeps the work linear in the number of layers. Use {@link beamSearch} when
46
+ * states do not repeat and the goal is a single best state rather than a path.
47
+ *
48
+ * Without `beamWidth`, the result is exact. With it, each layer keeps only its
49
+ * `beamWidth` cheapest states, so the result can miss the optimum.
50
+ *
51
+ * Time complexity: O(L · S · b) for `layerCount` L, states per layer S and
52
+ * successors per state b, plus O(L · S·b · log(S·b)) when `beamWidth` prunes.
53
+ * Memory: O(L · S) back-pointers.
54
+ *
55
+ * @example
56
+ * // Choose 0 or 1 at each of three steps, paying 1 to change value.
57
+ * const path = viterbi<number>(
58
+ * 0,
59
+ * {
60
+ * nextStatesOf: (value) => [
61
+ * { state: 0, cost: value === 0 ? 0 : 1 },
62
+ * { state: 1, cost: value === 1 ? 0 : 1 },
63
+ * ],
64
+ * keyOf: (value) => value,
65
+ * },
66
+ * 3,
67
+ * );
68
+ * // path: { states: [0, 0, 0], cost: 0 }
69
+ *
70
+ * @param initialState - The state before the first layer; not part of the
71
+ * returned path.
72
+ * @param traits - How to expand a state and identify equal states.
73
+ * @param layerCount - How many layers the path crosses.
74
+ * @param options - See {@link ViterbiOptions}.
75
+ * @returns The cheapest path, or `undefined` when every path reaches a dead end
76
+ * before the last layer. With `layerCount` 0, an empty path of cost 0.
77
+ */
78
+ export declare function viterbi<TState extends DefinedValue>(initialState: TState, traits: ViterbiTraits<TState>, layerCount: number, options?: ViterbiOptions): ViterbiPath<TState> | undefined;
79
+ //# sourceMappingURL=viterbi.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viterbi.d.ts","sourceRoot":"","sources":["../../src/optimize/viterbi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,6DAA6D;AAC7D,MAAM,MAAM,gBAAgB,CAAC,MAAM,IAAI;IACtC,KAAK,EAAE,MAAM,CAAC;IACd,kEAAkE;IAClE,IAAI,EAAE,MAAM,CAAC;CACb,CAAC;AAEF,qEAAqE;AACrE,MAAM,MAAM,aAAa,CAAC,MAAM,IAAI;IACnC;;;;OAIG;IACH,YAAY,CACX,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,GACX,SAAS,gBAAgB,CAAC,MAAM,CAAC,EAAE,CAAC;IAEvC;;;OAGG;IACH,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;CACtC,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC5B;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,oDAAoD;AACpD,MAAM,MAAM,WAAW,CAAC,MAAM,IAAI;IACjC,4DAA4D;IAC5D,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,8CAA8C;IAC9C,IAAI,EAAE,MAAM,CAAC;CACb,CAAC;AAKF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,wBAAgB,OAAO,CAAC,MAAM,SAAS,YAAY,EAClD,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,EAC7B,UAAU,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE,cAAc,GACtB,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CA0DjC"}
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The cheapest path through a layered state space: from `initialState`, one
3
+ * state per layer, minimising the summed transition cost.
4
+ *
5
+ * Reach for it when a sequence of decisions is scored step by step and many
6
+ * different histories end in the same state — decoding a hidden Markov model,
7
+ * fingering a passage chord by chord, assigning each item of a sequence a
8
+ * label. States with equal `keyOf` merge on the cheaper path, which is what
9
+ * keeps the work linear in the number of layers. Use {@link beamSearch} when
10
+ * states do not repeat and the goal is a single best state rather than a path.
11
+ *
12
+ * Without `beamWidth`, the result is exact. With it, each layer keeps only its
13
+ * `beamWidth` cheapest states, so the result can miss the optimum.
14
+ *
15
+ * Time complexity: O(L · S · b) for `layerCount` L, states per layer S and
16
+ * successors per state b, plus O(L · S·b · log(S·b)) when `beamWidth` prunes.
17
+ * Memory: O(L · S) back-pointers.
18
+ *
19
+ * @example
20
+ * // Choose 0 or 1 at each of three steps, paying 1 to change value.
21
+ * const path = viterbi<number>(
22
+ * 0,
23
+ * {
24
+ * nextStatesOf: (value) => [
25
+ * { state: 0, cost: value === 0 ? 0 : 1 },
26
+ * { state: 1, cost: value === 1 ? 0 : 1 },
27
+ * ],
28
+ * keyOf: (value) => value,
29
+ * },
30
+ * 3,
31
+ * );
32
+ * // path: { states: [0, 0, 0], cost: 0 }
33
+ *
34
+ * @param initialState - The state before the first layer; not part of the
35
+ * returned path.
36
+ * @param traits - How to expand a state and identify equal states.
37
+ * @param layerCount - How many layers the path crosses.
38
+ * @param options - See {@link ViterbiOptions}.
39
+ * @returns The cheapest path, or `undefined` when every path reaches a dead end
40
+ * before the last layer. With `layerCount` 0, an empty path of cost 0.
41
+ */
42
+ export function viterbi(initialState, traits, layerCount, options) {
43
+ const beamWidth = options?.beamWidth ?? Number.POSITIVE_INFINITY;
44
+ const layers = [];
45
+ let current = [
46
+ { state: initialState, cost: 0, previous: -1 },
47
+ ];
48
+ for (let layer = 0; layer < layerCount; layer++) {
49
+ const byKey = new Map();
50
+ for (const [index, { state, cost }] of current.entries()) {
51
+ for (const successor of traits.nextStatesOf(state, layer)) {
52
+ const key = traits.keyOf(successor.state);
53
+ const total = cost + successor.cost;
54
+ const known = byKey.get(key);
55
+ if (known === undefined || total < known.cost) {
56
+ byKey.set(key, {
57
+ state: successor.state,
58
+ cost: total,
59
+ previous: index,
60
+ });
61
+ }
62
+ }
63
+ }
64
+ let next = [...byKey.values()];
65
+ if (next.length === 0) {
66
+ return undefined;
67
+ }
68
+ if (next.length > beamWidth) {
69
+ next = next
70
+ .toSorted((entryA, entryB) => entryA.cost - entryB.cost)
71
+ .slice(0, beamWidth);
72
+ }
73
+ layers.push(next);
74
+ current = next;
75
+ }
76
+ if (layers.length === 0) {
77
+ return { states: [], cost: 0 };
78
+ }
79
+ let best = 0;
80
+ for (const [index, entry] of current.entries()) {
81
+ if (entry.cost < current[best].cost) {
82
+ best = index;
83
+ }
84
+ }
85
+ const states = [];
86
+ let index = best;
87
+ for (let layer = layers.length - 1; layer >= 0; layer--) {
88
+ const entry = layers[layer][index];
89
+ states.push(entry.state);
90
+ index = entry.previous;
91
+ }
92
+ states.reverse();
93
+ return { states, cost: current[best].cost };
94
+ }
95
+ //# sourceMappingURL=viterbi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viterbi.js","sourceRoot":"","sources":["../../src/optimize/viterbi.ts"],"names":[],"mappings":"AAgDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAE,CAAC,IAAI,EAAE,CAAC;AAC9C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ac-kit/algo",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
4
4
  "description": "Classic algorithms that work on your own types rather than on numbers: searching, sorting, grouping, graph traversal and string distance.",
5
5
  "keywords": [
6
6
  "algorithms",
@@ -47,7 +47,7 @@
47
47
  "dependencies": {
48
48
  "@ac-kit/core": "^0.7.0",
49
49
  "@ac-kit/data": "^0.2.0",
50
- "@types/web": "^0.0.362"
50
+ "@types/web": "^0.0.365"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@ac-kit/tsconfig": "0.1.0",