@raikuxq/alg-ds 2.0.0 → 3.0.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/README.md CHANGED
@@ -86,23 +86,23 @@ Extends [ILinearStorage](src/app/types/ILinearStorage.ts) interface.
86
86
  Extends [ILinearStorageRA](src/app/types/ILinearStorageRA.ts) and [IConvertableToArray](src/app/types/IConvertableToArray.ts) interface.
87
87
 
88
88
  ### Implementation
89
- [AbstractLinkedList](src/app/data-structures/LinkedList/AbstractLinkedList/AbstractLinkedList.ts) — Common logic for both single and double linked lists.
89
+ [AbstractLinkedList](src/app/data-structures/LinkedList/core/AbstractLinkedList/AbstractLinkedList.ts) — Common logic for both single and double linked lists.
90
90
  Implements [ILinearStorageRA](src/app/types/ILinearStorageRA.ts) interface.
91
91
 
92
- [SingleLinkedList](src/app/data-structures/LinkedList/SingleLinkedList/SingleLinkedList.ts)
92
+ [SingleLinkedList](src/app/data-structures/LinkedList/core/SingleLinkedList/SingleLinkedList.ts)
93
93
  [ [ tests ] ](test/unit/data-structures/linked-list/linked-list.test.ts)
94
94
  — Extends abstract linked list with implementation of one-way linking.
95
95
 
96
- [DoubleLinkedList](src/app/data-structures/LinkedList/DoubleLinkedList/DoubleLinkedList.ts)
96
+ [DoubleLinkedList](src/app/data-structures/LinkedList/core/DoubleLinkedList/DoubleLinkedList.ts)
97
97
  [ [ tests ] ](test/unit/data-structures/linked-list/linked-list.test.ts)
98
98
  — Extends abstract linked list with implementation of two-way linking.
99
99
 
100
- [IterableSingleLinkedList](src/app/data-structures/LinkedList/SingleLinkedList/IterableSingleLinkedList.ts)
100
+ [IterableSingleLinkedList](src/app/data-structures/LinkedList/core/SingleLinkedList/IterableSingleLinkedList.ts)
101
101
  [ [ tests ] ](test/unit/data-structures/linked-list/linked-list-iterable.test.ts)
102
102
  — Extends single linked list with iterator implementation.
103
103
  Implements [IIterable](src/app/types/IIterable.ts) interface.
104
104
 
105
- [IterableDoubleLinkedList](src/app/data-structures/LinkedList/DoubleLinkedList/IterableDoubleLinkedList.ts)
105
+ [IterableDoubleLinkedList](src/app/data-structures/LinkedList/core/DoubleLinkedList/IterableDoubleLinkedList.ts)
106
106
  [ [ tests ] ](test/unit/data-structures/linked-list/linked-list-iterable.test.ts)
107
107
  — Extends double linked list with implementation of two-way linking.
108
108
  Implements [IBiDirectIterable](src/app/types/IBiDirectIterable.ts) interface.
@@ -132,52 +132,52 @@ Implements [IBiDirectIterable](src/app/types/IBiDirectIterable.ts) interface.
132
132
  [IGraphIterationStrategy](src/app/types/IGraphIterationStrategy.ts) — Iteration strategies which are used in shortest-path, has-path.
133
133
 
134
134
  ### Implementation
135
- [GraphEdge](src/app/data-structures/Graph/GraphEdge.ts) — Contains from/to links and edge weight.
135
+ [GraphEdge](src/app/data-structures/Graph/core/GraphEdge.ts) — Contains from/to links and edge weight.
136
136
 
137
- [AbstractGraph](src/app/data-structures/Graph/AbstractGraph.ts) — Common logic for both directed and undirected graphs.
137
+ [AbstractGraph](src/app/data-structures/Graph/core/AbstractGraph.ts) — Common logic for both directed and undirected graphs.
138
138
 
139
139
 
140
- [DirectedGraph](src/app/data-structures/Graph/DirectedGraph.ts) [ [ tests ] ](test/unit/data-structures/graph/graph.test.ts)
140
+ [DirectedGraph](src/app/data-structures/Graph/core/DirectedGraph.ts) [ [ tests ] ](test/unit/data-structures/graph/graph.test.ts)
141
141
  — In case of directed graph A->B and B->A edges are not the same.
142
142
 
143
- [UndirectedGraph](src/app/data-structures/Graph/UndirectedGraph.ts) [ [ tests ] ](test/unit/data-structures/graph/graph.test.ts)
143
+ [UndirectedGraph](src/app/data-structures/Graph/core/UndirectedGraph.ts) [ [ tests ] ](test/unit/data-structures/graph/graph.test.ts)
144
144
  — In case of undirected graph A->B and B->A are equal.
145
145
 
146
146
 
147
147
  ### Graph Iterators
148
148
 
149
- [BreadthFirstSearchIterator](src/app/algorithms/graph/iterator/GraphIteratorBFS.ts)
149
+ [BreadthFirstSearchIterator](src/app/data-structures/Graph/iterator/GraphIteratorBFS.ts)
150
150
  — Traversal method for unweighted graphs, built on queue.
151
151
 
152
- [DepthFirstSearchIterator](src/app/algorithms/graph/iterator/GraphIteratorDFS.ts)
152
+ [DepthFirstSearchIterator](src/app/data-structures/Graph/iterator/GraphIteratorDFS.ts)
153
153
  — Traversal method for unweighted graphs, built on stack.
154
154
 
155
- [DijkstraMethodIterator](src/app/algorithms/graph/iterator/GraphIteratorDijkstra.ts)
155
+ [DijkstraMethodIterator](src/app/data-structures/Graph/iterator/GraphIteratorDijkstra.ts)
156
156
  — Traversal method for weighted graphs, built on finding the minimal cost.
157
157
 
158
158
 
159
159
  ### Graph Presenter
160
- [presenter-adjacency-lists](src/app/algorithms/graph/presenter/presenterAdjacencyLists.ts) [[ tests ](test/unit/data-structures/graph/graph.presenter.lists.test.ts)]
160
+ [presenter-adjacency-lists](src/app/data-structures/Graph/presenter/presenterAdjacencyLists.ts) [[ tests ](test/unit/data-structures/graph/graph.presenter.lists.test.ts)]
161
161
  — Representation of graph as an adjacency list (using Map).
162
162
 
163
- [presenter-adjacency-matrix](src/app/algorithms/graph/presenter/presenterAdjacencyMatrix.ts) [[ tests ](test/unit/data-structures/graph/graph.presenter.matrix.test.ts)]
163
+ [presenter-adjacency-matrix](src/app/data-structures/Graph/presenter/presenterAdjacencyMatrix.ts) [[ tests ](test/unit/data-structures/graph/graph.presenter.matrix.test.ts)]
164
164
  — Representation of graph as an adjacency matrix (using Array N*N).
165
165
 
166
166
 
167
167
  ### Graph Searching
168
- [has-path (BFS/DFS)](src/app/algorithms/graph/searching/hasPath.ts) [[ tests ](test/unit/data-structures/graph/graph.has-path.test.ts)]
168
+ [has-path (BFS/DFS)](src/app/data-structures/Graph/searching/hasPath.ts) [[ tests ](test/unit/data-structures/graph/graph.has-path.test.ts)]
169
169
  — Search for the existence of a path between two vertices.
170
170
 
171
- [shortest-path (BFS/Dijkstra)](src/app/algorithms/graph/searching/shortestPath.ts) [[ tests ](test/unit/data-structures/graph/graph.shortest-path.test.ts)]
171
+ [shortest-path (BFS/Dijkstra)](src/app/data-structures/Graph/searching/shortestPath.ts) [[ tests ](test/unit/data-structures/graph/graph.shortest-path.test.ts)]
172
172
  — Search for one of several shortest paths between two vertices.
173
173
 
174
174
  ### Graph Creators
175
- [create-graph-from-matrix](src/app/data-structures/Graph/_helpers/createGraphFromMatrix.ts) [[ tests ](test/unit/data-structures/graph/graph.create-from-matrix.test.ts)]
175
+ [create-graph-from-matrix](src/app/data-structures/Graph/factories/createGraphFromMatrix.ts) [[ tests ](test/unit/data-structures/graph/graph.create-from-matrix.test.ts)]
176
176
  — Convert a matrix N*N into a graph instance.
177
177
 
178
178
 
179
179
  ### Graph Transposing
180
- [transpose-directed-graph](src/app/algorithms/graph/transposing/transposeDirectedGraph.ts) [ [ tests ](test/unit/data-structures/graph/graph.transpose.test.ts)]
180
+ [transpose-directed-graph](src/app/data-structures/Graph/transposing/transposeDirectedGraph.ts) [ [ tests ](test/unit/data-structures/graph/graph.transpose.test.ts)]
181
181
  — Transpose a directed graph (undirected graphs are symmetrical already).
182
182
 
183
183
 
@@ -187,23 +187,23 @@ Implements [IBiDirectIterable](src/app/types/IBiDirectIterable.ts) interface.
187
187
 
188
188
  ### Implementation
189
189
 
190
- [AbstractBinaryNode](src/app/data-structures/BinaryTree/AbstractBinaryTree/AbstractBinaryNode.ts) — Contains left/right/parent links and node data.
190
+ [AbstractBinaryNode](src/app/data-structures/BinaryTree/core/AbstractBinaryTree/AbstractBinaryNode.ts) — Contains left/right/parent links and node data.
191
191
 
192
- [AbstractBinaryTree](src/app/data-structures/BinaryTree/AbstractBinaryTree/AbstractBinaryTree.ts) — Common logic for all types of binary trees.
192
+ [AbstractBinaryTree](src/app/data-structures/BinaryTree/core/AbstractBinaryTree/AbstractBinaryTree.ts) — Common logic for all types of binary trees.
193
193
 
194
194
 
195
- [BinarySearchNode](src/app/data-structures/BinaryTree/BinarySearchTree/BinarySearchNode.ts) — Same as abstract binary node.
195
+ [BinarySearchNode](src/app/data-structures/BinaryTree/core/BinarySearchTree/BinarySearchNode.ts) — Same as abstract binary node.
196
196
 
197
- [BinarySearchTree](src/app/data-structures/BinaryTree/BinarySearchTree/BinarySearchTree.ts) — Implementation of unbalanced binary search tree.
197
+ [BinarySearchTree](src/app/data-structures/BinaryTree/core/BinarySearchTree/BinarySearchTree.ts) — Implementation of unbalanced binary search tree.
198
198
  Each node in left subtree is smaller and each node in right subtree is larger than the node data.
199
- Extends [AbstractSearchTree](src/app/data-structures/BinaryTree/AbstractBinaryTree/AbstractBinaryTree.ts).
199
+ Extends [AbstractSearchTree](src/app/data-structures/BinaryTree/core/AbstractBinaryTree/AbstractBinaryTree.ts).
200
200
 
201
201
 
202
202
 
203
- [RandBinarySearchNode](src/app/data-structures/BinaryTree/RandBinarySearchTree/RandBinarySearchNode.ts) — Have a rank attribute.
204
- Extends [BinarySearchNode](src/app/data-structures/BinaryTree/BinarySearchTree/BinarySearchNode.ts).
203
+ [RandBinarySearchNode](src/app/data-structures/BinaryTree/core/RandBinarySearchTree/RandBinarySearchNode.ts) — Have a rank attribute.
204
+ Extends [BinarySearchNode](src/app/data-structures/BinaryTree/core/BinarySearchTree/BinarySearchNode.ts).
205
205
 
206
- [RandBinarySearchTree](src/app/data-structures/BinaryTree/RandBinarySearchTree/RandBinarySearchTree.ts)
206
+ [RandBinarySearchTree](src/app/data-structures/BinaryTree/core/RandBinarySearchTree/RandBinarySearchTree.ts)
207
207
  — Implementation of randomized binary search tree, which gives expected log(N) height.
208
208
  INSERTION have a 1/N+1 probability of inserting into root.
209
- Extends [BinarySearchTree](src/app/data-structures/BinaryTree/BinarySearchTree/BinarySearchTree.ts).
209
+ Extends [BinarySearchTree](src/app/data-structures/BinaryTree/core/BinarySearchTree/BinarySearchTree.ts).
package/lib/index.d.ts CHANGED
@@ -1,20 +1,22 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
+ export declare const EDGE_EXISTS_STATE = 1;
4
+ export declare const EDGE_NOT_EXISTS_STATE = 0;
3
5
  export type FnToMemoize<Key, Value> = (...args: Array<Key>) => Value;
4
6
  /**
5
- * Time complexity: O(n!)
7
+ * Time complexity: O(n)
6
8
  */
7
9
  export declare const factorial: (x: number) => number;
8
10
  /**
9
- * Time complexity: O(n) - due to caching
11
+ * Time complexity: O(n) for the first call, O(1) for cached calls
10
12
  */
11
13
  export declare const memoizedFactorial: FnToMemoize<number, number>;
12
14
  /**
13
- * Time complexity: O(n!)
15
+ * Time complexity: O(2^n) - exponential without memoization
14
16
  */
15
17
  export declare const fibonacci: (n: number) => number;
16
18
  /**
17
- * Time complexity: O(n) - due to caching
19
+ * Time complexity: O(n) - linear due to caching
18
20
  */
19
21
  export declare const memoizedFibonacci: FnToMemoize<number, number>;
20
22
  /**
@@ -28,7 +30,7 @@ export type TypeArrayMatrix = Array<Array<number>>;
28
30
  * @throws {IllegalArgumentException} when array is not a matrix
29
31
  */
30
32
  export declare const transposeMatrix: (matrix: TypeArrayMatrix) => TypeArrayMatrix;
31
- export interface IGraph<T> {
33
+ export interface IGraph<T> extends Iterable<T> {
32
34
  weight(): number;
33
35
  vertices(): Array<T>;
34
36
  verticesCount(): number;
@@ -67,18 +69,6 @@ export interface IGraphIterator<T> extends IIterator<T> {
67
69
  */
68
70
  initIterator(from: T): void;
69
71
  }
70
- export interface IGraphIterationStrategy<T> {
71
- createIterator(graph: IGraph<T>): IGraphIterator<T>;
72
- }
73
- export declare class BFSIterationStrategy<T> implements IGraphIterationStrategy<T> {
74
- createIterator(graph: IGraph<T>): IGraphIterator<T>;
75
- }
76
- export declare class DFSIterationStrategy<T> implements IGraphIterationStrategy<T> {
77
- createIterator(graph: IGraph<T>): IGraphIterator<T>;
78
- }
79
- export declare class DijkstraIterationStrategy<T> implements IGraphIterationStrategy<T> {
80
- createIterator(graph: IGraph<T>): IGraphIterator<T>;
81
- }
82
72
  declare abstract class AbstractGraphIterator<T> implements IGraphIterator<T> {
83
73
  protected readonly graph: IGraph<T>;
84
74
  protected readonly visited: Map<T, boolean>;
@@ -169,18 +159,15 @@ export declare class GraphIteratorDFS<T> extends AbstractGraphIterator<T> {
169
159
  nextImpl(): T;
170
160
  }
171
161
  /**
172
- * Dijkstra method graph traversal
162
+ * Dijkstra method graph traversal using a Priority Queue.
173
163
  */
174
164
  export declare class GraphIteratorDijkstra<T> extends AbstractGraphIterator<T> {
175
165
  private readonly costs;
166
+ private readonly queue;
176
167
  /**
177
168
  * @inheritDoc
178
169
  */
179
170
  constructor(graph: IGraph<T>);
180
- /**
181
- * Get not visited vertex with minimal cost
182
- */
183
- private getClosestNotVisited;
184
171
  /**
185
172
  * @inheritDoc
186
173
  */
@@ -197,21 +184,44 @@ export declare class GraphIteratorDijkstra<T> extends AbstractGraphIterator<T> {
197
184
  * @inheritDoc
198
185
  */
199
186
  nextImpl(): T;
187
+ /**
188
+ * Removes stale entries from the queue top.
189
+ */
190
+ private refreshQueue;
191
+ }
192
+ declare enum EnumGraphTraversalType {
193
+ BFS = "Breadth first traversal",
194
+ DFS = "Deep first traversal",
195
+ DIJKSTRA = "Dijkstra traversal"
200
196
  }
197
+ /**
198
+ * Creates a graph iterator based on the specified traversal mode.
199
+ */
200
+ export declare const createGraphIterator: <T>(graph: IGraph<T>, mode: EnumGraphTraversalType) => IGraphIterator<T>;
201
201
  /**
202
202
  * Check if graph has a path between two vertices
203
203
  * @throws {IsNotFoundException} when start vertex was not found
204
204
  * @throws {IsNotFoundException} when end vertex was not found
205
205
  * @throws {IllegalStateException} when there is no path between two vertices
206
206
  */
207
- export declare const hasPath: <T>(graph: IGraph<T>, from: T, to: T, strategy: IGraphIterationStrategy<T>) => boolean;
207
+ export declare const hasPath: <T>({ graph, traversalType, from, to, }: {
208
+ graph: IGraph<T>;
209
+ from: T;
210
+ to: T;
211
+ traversalType: EnumGraphTraversalType;
212
+ }) => boolean;
208
213
  /**
209
214
  * Find the shortest path between two vertices
210
215
  * @throws {IsNotFoundException} when start vertex was not found
211
216
  * @throws {IsNotFoundException} when end vertex was not found
212
217
  * @throws {IllegalStateException} when there is no path between two vertices
213
218
  */
214
- export declare const shortestPath: <T>(graph: IGraph<T>, from: T, to: T, strategy: IGraphIterationStrategy<T>) => Array<T>;
219
+ export declare const shortestPath: <T>({ graph, traversalType, from, to, }: {
220
+ graph: IGraph<T>;
221
+ from: T;
222
+ to: T;
223
+ traversalType: EnumGraphTraversalType;
224
+ }) => Array<T>;
215
225
  /**
216
226
  * Get graph adjacency matrix N x N
217
227
  *
@@ -231,7 +241,7 @@ export declare const shortestPath: <T>(graph: IGraph<T>, from: T, to: T, strateg
231
241
  * @example
232
242
  *
233
243
  * Undirected graph:
234
- * - Bob [Maria]
244
+ * - Bob [Mariaэ
235
245
  * - Maria [Bob, John]
236
246
  * - John [Maria]
237
247
  *
@@ -260,15 +270,6 @@ export declare const presenterAdjacencyMatrix: <T>(graph: IGraph<T>) => TypeArra
260
270
  * - John [Maria]
261
271
  **/
262
272
  export declare const presenterAdjacencyLists: <T>(graph: IGraph<T>) => Map<T, Array<T>>;
263
- declare enum EnumGraphType {
264
- DIRECTED = "DIRECTED",
265
- UNDIRECTED = "UNDIRECTED"
266
- }
267
- declare enum EnumRandomGenerationFormat {
268
- NUMBERS = "NUMBERS",
269
- HASH = "HASH"
270
- }
271
- export declare const generateRandomGraph: (verticesCount: number, edgesCount: number, type?: EnumGraphType, format?: EnumRandomGenerationFormat) => IGraph<string>;
272
273
  declare enum EnumLinkedListType {
273
274
  DOUBLE = "Double linked list",
274
275
  SINGLE = "Single linked list"
@@ -300,7 +301,7 @@ export interface IConvertableToArray<T> {
300
301
  pushFromArray(elements: Array<T>): void;
301
302
  getAsArray(): Array<T>;
302
303
  }
303
- export interface ILinkedList<T> extends ILinearStorageRA<T>, IConvertableToArray<T> {
304
+ export interface ILinkedList<T> extends ILinearStorageRA<T>, IConvertableToArray<T>, Iterable<T> {
304
305
  }
305
306
  export declare const createLinkedList: <T>(type: EnumLinkedListType, isIterable?: boolean, capacity?: number) => ILinkedList<T>;
306
307
  declare enum EnumBinarySearchTreeType {
@@ -327,6 +328,10 @@ export interface IBinaryTree<T> {
327
328
  * Returns binary tree by type
328
329
  */
329
330
  export declare const createBinaryTree: <T>(type: EnumBinarySearchTreeType) => IBinaryTree<T>;
331
+ declare enum EnumGraphType {
332
+ DIRECTED = "DIRECTED",
333
+ UNDIRECTED = "UNDIRECTED"
334
+ }
330
335
  /**
331
336
  * Returns graph by type
332
337
  */
@@ -335,8 +340,6 @@ export declare const createGraph: <T>(type: EnumGraphType) => IGraph<T>;
335
340
  * Creates a graph from N*N matrix that contains 1 in case of edge exists or 0 in case it does not
336
341
  */
337
342
  export declare const createGraphFromMatrix: <T>(matrix: TypeArrayMatrix, fieldsList: Array<T>, type: EnumGraphType) => IGraph<T>;
338
- export declare const EDGE_EXISTS_STATE = 1;
339
- export declare const EDGE_NOT_EXISTS_STATE = 0;
340
343
  /**
341
344
  * FIFO data structure
342
345
  */
@@ -386,204 +389,91 @@ export declare class Queue<T> implements ILinearStorage<T> {
386
389
  */
387
390
  reverse(): void;
388
391
  }
389
- /**
390
- * LIFO data structure
391
- */
392
- export declare class Stack<T> implements ILinearStorage<T> {
393
- private readonly _list;
394
- /**
395
- * Create a stack instance
396
- */
392
+ export declare class Stack<T> implements ILinearStorage<T>, Iterable<T> {
393
+ private readonly _items;
394
+ private readonly _capacity;
397
395
  constructor(capacity?: number);
398
- /**
399
- * Get stack top element
400
- * @throws {CollectionIsEmptyException} when list is empty
401
- */
396
+ length(): number;
397
+ isEmpty(): boolean;
398
+ isFull(): boolean;
402
399
  peek(): T;
403
- /**
404
- * Add element to stack head
405
- * @throws {CollectionIsFullException} when list is full
406
- */
407
400
  push(item: T): void;
408
- /**
409
- * Remove element from stack head
410
- * @throws {CollectionIsEmptyException} when list is empty
411
- */
412
401
  pop(): T;
413
- /**
414
- * Check if element exists in list
415
- */
416
402
  has(item: T): boolean;
417
- /**
418
- * Is stack empty
419
- */
420
- isEmpty(): boolean;
421
- /**
422
- * Is stack full
423
- */
424
- isFull(): boolean;
425
- /**
426
- * Remove all elements in stack
427
- */
428
403
  clear(): void;
429
- /**
430
- * Queue length
431
- */
432
- length(): number;
433
- /**
434
- * Reverse stack
435
- */
436
404
  reverse(): void;
437
- }
438
- declare class GraphEdge<T> {
439
- private readonly _fromVertex;
440
- private readonly _toVertex;
441
- private _weight;
442
- /**
443
- * Create instance with linked "from" and "to" vertices
444
- */
445
- constructor(fromVertex: T, toVertex: T, weight?: number);
446
- get fromVertex(): T;
447
- get toVertex(): T;
448
- get weight(): number;
449
- set weight(value: number);
450
- }
451
- declare abstract class AbstractGraph<T> {
452
- protected _vertices: Map<T, Array<T>>;
453
- protected _edges: Array<GraphEdge<T>>;
454
- /**
455
- * Created empty instance
456
- */
457
- protected constructor();
458
- /**
459
- * Find edge by its from and to vertices
460
- */
461
- protected abstract getEdgeByValue(from: T, to: T): GraphEdge<T>;
462
- /**
463
- * Get vertices list in array format
464
- */
465
- protected getVerticesArrayFormat(): Array<T>;
466
- /**
467
- * Find vertex in vertices list by its data
468
- * @throws {IsNotFoundException} when vertex was not found
469
- */
470
- protected tryFindVertex(data: T): T;
471
- /**
472
- * Update edge weight between from and to vertices
473
- */
474
- protected updateEdgeWeight(from: T, to: T, weight: number): void;
475
- /**
476
- * Will remove all vertex relations with others vertices
477
- */
478
- protected cascadeRemoveVertexRelations(vertexToRemove: T): void;
479
- /**
480
- * Will remove all vertices edges with vertex to remove
481
- */
482
- protected cascadeRemoveVertexEdges(vertexToRemove: T): void;
483
- /**
484
- * Get sum of all graph edges
485
- */
486
- weight(): number;
487
- /**
488
- * Get array of vertices
489
- */
490
- vertices(): Array<T>;
491
- /**
492
- * Get vertices count
493
- */
494
- verticesCount(): number;
495
- /**
496
- * Get edges count
497
- */
498
- edgesCount(): number;
499
- /**
500
- * Add vertex
501
- * @throws {IsAlreadyExistsException} when vertex is already exists
502
- */
503
- addVertex(data: T): this;
504
- /**
505
- * Remove vertex
506
- * @throws {IsNotFoundException} when vertex is already does not exist
507
- */
508
- removeVertex(data: T): this;
509
- /**
510
- * Add edge between two vertices
511
- */
512
- abstract addEdge(from: T, to: T, weight?: number): this;
513
- /**
514
- * Remove edge between two vertices
515
- */
516
- abstract removeEdge(from: T, to: T): this;
517
- /**
518
- * Get vertex neighbors by its data
519
- */
520
- getVertexNeighbors(data: T): Array<T>;
521
- /**
522
- * Check if graph has vertex
523
- */
524
- hasVertex(data: T): boolean;
525
- /**
526
- * Check if graph has edge between from and to vertices
527
- */
528
- hasEdge(from: T, to: T): boolean;
529
- /**
530
- * Get edge weight between from and to vertices
531
- */
532
- getEdgeWeight(from: T, to: T): number;
405
+ [Symbol.iterator](): Iterator<T>;
533
406
  }
534
407
  /**
535
- * Undirected graph - data structure where edges with same pair of vertices are equal
536
- * @example A-B is same as B-A
408
+ * A Priority Queue implementation based on a Min-Binary Heap.
409
+ * Lower priority numbers are dequeued first.
537
410
  */
538
- export declare class UndirectedGraph<T> extends AbstractGraph<T> {
539
- /**
540
- * @inheritDoc
541
- */
411
+ export declare class PriorityQueue<T> {
412
+ private readonly _heap;
542
413
  constructor();
414
+ /** Number of elements in the queue. */
415
+ get size(): number;
416
+ /** Returns true if the queue is empty. */
417
+ isEmpty(): boolean;
543
418
  /**
544
- * @inheritDoc
545
- * @throws {IsNotFoundException} when vertex was not found
546
- */
547
- protected getEdgeByValue(from: T, to: T): GraphEdge<T>;
548
- /**
549
- * @inheritDoc
419
+ * Adds an element to the queue with a specific priority.
420
+ * @param value The data to store.
421
+ * @param priority The priority level (lower value = higher priority).
550
422
  */
551
- hasEdge(from: T, to: T): boolean;
423
+ enqueue(value: T, priority: number): void;
552
424
  /**
553
- * @inheritDoc
554
- * @throws {IsNotFoundException} when vertex was not found
425
+ * Removes and returns the element with the highest priority (lowest priority number).
426
+ * @throws {CollectionIsEmptyException} If the queue is empty.
555
427
  */
556
- addEdge(from: T, to: T, weight?: number): this;
428
+ dequeue(): T;
557
429
  /**
558
- * @inheritDoc
559
- * @throws {IsNotFoundException} when vertex was not found
430
+ * Returns the highest priority element without removing it.
431
+ * @throws {CollectionIsEmptyException} If the queue is empty.
560
432
  */
561
- removeEdge(from: T, to: T): this;
433
+ peek(): T;
434
+ /** Clears all elements from the queue. */
435
+ clear(): void;
562
436
  }
563
437
  /**
564
- * Directed graph - data structure where edges with same pair of vertices are not equal
565
- * @example A-B is not the same as B-A
438
+ * A Binary Heap implementation supporting custom priority logic
566
439
  */
567
- export declare class DirectedGraph<T> extends AbstractGraph<T> {
440
+ export declare class BinaryHeap<T> {
441
+ private readonly _heap;
442
+ private readonly _comparator;
568
443
  /**
569
- * @inheritDoc
444
+ * @param comparator Function to determine element priority
570
445
  */
571
- constructor();
446
+ constructor(comparator?: (a: T, b: T) => number);
447
+ /** Current number of elements in the heap */
448
+ get size(): number;
449
+ /** Returns true if the heap contains no elements */
450
+ isEmpty(): boolean;
572
451
  /**
573
- * @inheritDoc
574
- * @throws {IsNotFoundException} when vertex was not found
452
+ * Retrieves the root element without removing it
453
+ * @throws {CollectionIsEmptyException} If the heap is empty.
575
454
  */
576
- protected getEdgeByValue(from: T, to: T): GraphEdge<T>;
455
+ peek(): T;
577
456
  /**
578
- * @inheritDoc
579
- * @throws {IsNotFoundException} when vertex was not found
457
+ * Adds a new value and restores heap properties
580
458
  */
581
- addEdge(from: T, to: T, weight?: number): this;
459
+ insert(value: T): void;
582
460
  /**
583
- * @inheritDoc
584
- * @throws {IsNotFoundException} when vertex was not found
585
- */
586
- removeEdge(from: T, to: T): this;
461
+ * Removes and returns the root element (minimum based on comparator)
462
+ * @throws {CollectionIsEmptyException} If the heap is empty.
463
+ */
464
+ extractMin(): T;
465
+ /** Default comparison for primitive types */
466
+ private defaultComparator;
467
+ private parentIndex;
468
+ private leftChildIndex;
469
+ private rightChildIndex;
470
+ private swap;
471
+ /** Moves an element up until heap properties are restored */
472
+ private bubbleUp;
473
+ /** Moves an element down until heap properties are restored */
474
+ private bubbleDown;
475
+ /** Returns an iterator over the underlying array */
476
+ [Symbol.iterator](): IterableIterator<T>;
587
477
  }
588
478
  export type FnCompareTwo<T> = (firstItem: T, secondItem: T) => boolean;
589
479
  declare abstract class AbstractBinaryNode<T> {
@@ -731,6 +621,9 @@ export declare class BinarySearchTree<T> extends AbstractBinaryTree<T> {
731
621
  * @throws {CollectionIsEmptyException} when tree is empty
732
622
  */
733
623
  traverse(type: EnumTreeTraversalType, from?: T): Array<T>;
624
+ private storeInOrder;
625
+ private storePreOrder;
626
+ private storePostOrder;
734
627
  /**
735
628
  * Calc max height of the largest branch of the tree
736
629
  */
@@ -957,6 +850,10 @@ declare abstract class AbstractLinkedList<T> implements ILinkedList<T> {
957
850
  * @example "4>7>10" will be reversed to "10>7>4"
958
851
  */
959
852
  abstract reverse(): void;
853
+ /**
854
+ * Iterator
855
+ */
856
+ [Symbol.iterator](): IterableIterator<T>;
960
857
  }
961
858
  declare class DoubleLinkedNode<T> extends AbstractLinkedNode<T> {
962
859
  protected _prev: DoubleLinkedNode<T> | null;
@@ -1118,6 +1015,172 @@ export declare class IterableDoubleLinkedList<T> extends DoubleLinkedList<T> imp
1118
1015
  */
1119
1016
  iterator(fromIndex?: number): IBiDirectIterator<T>;
1120
1017
  }
1018
+ declare class GraphEdge<T> {
1019
+ private readonly _fromVertex;
1020
+ private readonly _toVertex;
1021
+ private _weight;
1022
+ /**
1023
+ * Create instance with linked "from" and "to" vertices
1024
+ */
1025
+ constructor(fromVertex: T, toVertex: T, weight?: number);
1026
+ get fromVertex(): T;
1027
+ get toVertex(): T;
1028
+ get weight(): number;
1029
+ set weight(value: number);
1030
+ }
1031
+ declare abstract class AbstractGraph<T> {
1032
+ protected _vertices: Map<T, Set<T>>;
1033
+ protected _edges: Map<string, GraphEdge<T>>;
1034
+ /**
1035
+ * Created empty instance
1036
+ */
1037
+ protected constructor();
1038
+ protected static readonly EDGE_KEY_SEPARATOR: string;
1039
+ /**
1040
+ * Get edge key string from_to
1041
+ * @example Bob_Maria
1042
+ * @example Maria_Bob
1043
+ */
1044
+ protected getEdgeKey(from: T, to: T): string;
1045
+ /**
1046
+ * Find edge by its from and to vertices
1047
+ */
1048
+ protected abstract getEdgeByValue(from: T, to: T): GraphEdge<T>;
1049
+ /**
1050
+ * Get vertices list in array format
1051
+ */
1052
+ protected getVerticesArrayFormat(): Array<T>;
1053
+ /**
1054
+ * Find vertex in vertices list by its data
1055
+ * @throws {IsNotFoundException} when vertex was not found
1056
+ */
1057
+ protected tryFindVertex(data: T): T;
1058
+ /**
1059
+ * Update edge weight between from and to vertices
1060
+ */
1061
+ protected updateEdgeWeight(from: T, to: T, weight: number): void;
1062
+ /**
1063
+ * Will remove all vertex relations with others vertices
1064
+ */
1065
+ protected cascadeRemoveVertexRelations(vertexToRemove: T): void;
1066
+ /**
1067
+ * Will remove all vertices edges with vertex to remove
1068
+ */
1069
+ protected cascadeRemoveVertexEdges(vertexToRemove: T): void;
1070
+ /**
1071
+ * Get sum of all graph edges
1072
+ */
1073
+ weight(): number;
1074
+ /**
1075
+ * Get array of vertices
1076
+ */
1077
+ vertices(): Array<T>;
1078
+ /**
1079
+ * Get vertices count
1080
+ */
1081
+ verticesCount(): number;
1082
+ /**
1083
+ * Get edges count
1084
+ */
1085
+ edgesCount(): number;
1086
+ /**
1087
+ * Add vertex
1088
+ * @throws {IsAlreadyExistsException} when vertex is already exists
1089
+ */
1090
+ addVertex(data: T): this;
1091
+ /**
1092
+ * Remove vertex
1093
+ * @throws {IsNotFoundException} when vertex is already does not exist
1094
+ */
1095
+ removeVertex(data: T): this;
1096
+ /**
1097
+ * Add edge between two vertices
1098
+ */
1099
+ abstract addEdge(from: T, to: T, weight?: number): this;
1100
+ /**
1101
+ * Remove edge between two vertices
1102
+ */
1103
+ abstract removeEdge(from: T, to: T): this;
1104
+ /**
1105
+ * Get vertex neighbors by its data
1106
+ */
1107
+ getVertexNeighbors(data: T): Array<T>;
1108
+ /**
1109
+ * Check if graph has vertex
1110
+ */
1111
+ hasVertex(data: T): boolean;
1112
+ /**
1113
+ * Check if graph has edge between from and to vertices
1114
+ */
1115
+ hasEdge(from: T, to: T): boolean;
1116
+ /**
1117
+ * Get edge weight between from and to vertices
1118
+ */
1119
+ getEdgeWeight(from: T, to: T): number;
1120
+ /**
1121
+ * Iterator
1122
+ */
1123
+ [Symbol.iterator](): IterableIterator<T>;
1124
+ }
1125
+ /**
1126
+ * Directed graph - data structure where edges with same pair of vertices are not equal
1127
+ * @example A-B is not the same as B-A
1128
+ */
1129
+ export declare class DirectedGraph<T> extends AbstractGraph<T> {
1130
+ /**
1131
+ * @inheritDoc
1132
+ */
1133
+ constructor();
1134
+ /**
1135
+ * @inheritDoc
1136
+ * @throws {IsNotFoundException} when vertex was not found
1137
+ */
1138
+ protected getEdgeByValue(from: T, to: T): GraphEdge<T>;
1139
+ /**
1140
+ * @inheritDoc
1141
+ * @throws {IsNotFoundException} when vertex was not found
1142
+ */
1143
+ addEdge(from: T, to: T, weight?: number): this;
1144
+ /**
1145
+ * @inheritDoc
1146
+ * @throws {IsNotFoundException} when vertex was not found
1147
+ */
1148
+ removeEdge(from: T, to: T): this;
1149
+ /**
1150
+ * @inheritDoc
1151
+ */
1152
+ removeVertex(value: T): this;
1153
+ }
1154
+ /**
1155
+ * Undirected graph - data structure where edges with same pair of vertices are equal
1156
+ * @example A-B is same as B-A
1157
+ */
1158
+ export declare class UndirectedGraph<T> extends AbstractGraph<T> {
1159
+ /**
1160
+ * @inheritDoc
1161
+ */
1162
+ constructor();
1163
+ protected getEdgeKey(from: T, to: T): string;
1164
+ /**
1165
+ * @inheritDoc
1166
+ * @throws {IsNotFoundException} when vertex was not found
1167
+ */
1168
+ protected getEdgeByValue(from: T, to: T): GraphEdge<T>;
1169
+ /**
1170
+ * @inheritDoc
1171
+ */
1172
+ hasEdge(from: T, to: T): boolean;
1173
+ /**
1174
+ * @inheritDoc
1175
+ * @throws {IsNotFoundException} when vertex was not found
1176
+ */
1177
+ addEdge(from: T, to: T, weight?: number): this;
1178
+ /**
1179
+ * @inheritDoc
1180
+ * @throws {IsNotFoundException} when vertex was not found
1181
+ */
1182
+ removeEdge(from: T, to: T): this;
1183
+ }
1121
1184
  export declare class IllegalStateException extends Error {
1122
1185
  constructor(message: string);
1123
1186
  }
@@ -1200,17 +1263,17 @@ export declare const getMinIndex: (arr: Array<number>) => number;
1200
1263
  */
1201
1264
  export declare const getMinIndexFromIndex: (arr: Array<number>, fromIndex: number) => number;
1202
1265
  /**
1203
- * Will swap two items in array
1204
- * @example swapArrayItems([2,3,5], 1, 2) -> [2,5,3]
1266
+ * Round number to given digits after
1205
1267
  */
1206
- export declare const swapArrayItems: <T>(arr: Array<T>, leftIndex: number, rightIndex: number) => void;
1268
+ export declare const roundNumber: (num: number, digits?: number) => number;
1207
1269
  /**
1208
1270
  * Get random number in range
1209
1271
  */
1210
1272
  export declare const randomizeNumberInRange: (min: number, max: number) => number;
1211
1273
  /**
1212
- * Round number to given digits after
1274
+ * Will swap two items in array
1275
+ * @example swapArrayItems([2,3,5], 1, 2) -> [2,5,3]
1213
1276
  */
1214
- export declare const roundNumber: (num: number, digits?: number) => number;
1277
+ export declare const swapArrayItems: <T>(arr: Array<T>, leftIndex: number, rightIndex: number) => void;
1215
1278
 
1216
1279
  export {};
package/lib/index.mjs CHANGED
@@ -1 +1 @@
1
- const t=t=>{const e=/* @__PURE__ */new Map;return(...s)=>{const r=JSON.stringify(s);if(!e.has(r)){const i=t(...s);e.set(r,i)}return e.get(r)}},e=t=>t>1?t*e(t-1):t,s=t(t=>t>1?t*s(t-1):t),r=t=>t>1?r(t-1)+r(t-2):t,i=t(t=>t>1?i(t-1)+i(t-2):t),n=(t,e)=>{let s=0,r=t.length-1;for(;s<=r;){const i=Math.ceil((s+r)/2),n=t[i];if(e==n)return i;n>e?r=i-1:n<e&&(s=i+1)}return null};class h extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,h.prototype)}}const a=t=>t.reduce((e,s,r)=>s<t[e]?r:e,0),o=(t,e)=>e+a(t.slice(e)),l=(t,e,s)=>{if(e!==s){const r=t[e];t[e]=t[s],t[s]=r}},d=(t,e)=>Math.floor(Math.random()*(e-t))+t,u=(t,e=3)=>Math.round(t*10**e)/10**e,c=t=>{for(let e=0;e<t.length;e++){if(!(t[e].length===t.length))return!1}return!0},p=t=>{if(!c(t))throw new h("Given array is not a matrix");return t.reduce((e,s,r)=>(e[r]=t.map(t=>t[r]),e),new Array(t.length))};var g=/* @__PURE__ */(t=>(t.DIRECTED="DIRECTED",t.UNDIRECTED="UNDIRECTED",t))(g||{});class _ extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,_.prototype)}}class f extends _{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,f.prototype)}}class x extends _{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,x.prototype)}}class w{_vertices;_edges;constructor(){this._vertices=/* @__PURE__ */new Map,this._edges=new Array}getVerticesArrayFormat(){return Array.from(this._vertices.keys())}tryFindVertex(t){if(!this._vertices.has(t))throw new f("Vertex not found");return t}updateEdgeWeight(t,e,s){this.getEdgeByValue(t,e).weight=s}cascadeRemoveVertexRelations(t){this.getVerticesArrayFormat().forEach(e=>{const s=this._vertices.get(e);if(s){const r=s.filter(e=>e!==t);this._vertices.set(e,r)}})}cascadeRemoveVertexEdges(t){this._edges=this._edges.filter(e=>!(e.toVertex===t||e.fromVertex===t))}weight(){return this._edges.reduce((t,e)=>t+e.weight,0)}vertices(){return this.getVerticesArrayFormat().map(t=>t)}verticesCount(){return this.vertices().length}edgesCount(){return this._edges.length}addVertex(t){if(this.hasVertex(t))throw new x("Vertex is already exist");return this._vertices.set(t,new Array),this}removeVertex(t){try{const e=this.tryFindVertex(t);this.cascadeRemoveVertexEdges(e),this.cascadeRemoveVertexRelations(e),this._vertices.delete(e)}catch(e){throw new f("Vertex does not exist already")}return this}getVertexNeighbors(t){const e=this.tryFindVertex(t);return this._vertices.get(e)||[]}hasVertex(t){return this._vertices.has(t)}hasEdge(t,e){return Boolean(this._edges.find(s=>s.fromVertex===t&&s.toVertex===e))}getEdgeWeight(t,e){const s=this.tryFindVertex(t),r=this.tryFindVertex(e);return this.getEdgeByValue(s,r).weight}}class m{_fromVertex;_toVertex;_weight;constructor(t,e,s=0){this._fromVertex=t,this._toVertex=e,this._weight=s}get fromVertex(){return this._fromVertex}get toVertex(){return this._toVertex}get weight(){return this._weight}set weight(t){this._weight=t}}class E extends w{constructor(){super()}getEdgeByValue(t,e){const s=this._edges.find(s=>s.fromVertex===t&&s.toVertex===e);if(!s)throw new f("Edge not found");return s}addEdge(t,e,s){try{const r=this.tryFindVertex(t),i=this.tryFindVertex(e);if(this.hasEdge(r,i))"number"==typeof s&&this.updateEdgeWeight(r,i,s);else{const t=new m(r,i,s);this._edges.push(t),this._vertices.get(r)?.push(i)}}catch{throw new f("Edge cannot be added because one of vertices was not found")}return this}removeEdge(t,e){try{const s=this.tryFindVertex(t),r=this.tryFindVertex(e),i=this.getEdgeByValue(s,r),n=(this._vertices.get(s)||[]).filter(t=>r!==t);this._vertices.set(s,n),this._edges=this._edges.filter(t=>t!==i)}catch{throw new f("Edge cannot be removed because one of vertices was not found")}return this}}class y extends w{constructor(){super()}getEdgeByValue(t,e){const s=this._edges.find(s=>s.fromVertex===t&&s.toVertex===e||s.fromVertex===e&&s.toVertex===t);if(!s)throw new f("Edge not found");return s}hasEdge(t,e){return Boolean(this._edges.find(s=>s.fromVertex===t&&s.toVertex===e||s.fromVertex===e&&s.toVertex===t))}addEdge(t,e,s){try{const r=this.tryFindVertex(t),i=this.tryFindVertex(e);if(this.hasEdge(r,i))"number"==typeof s&&this.updateEdgeWeight(r,i,s);else{const t=new m(r,i,s);this._edges.push(t),this._vertices.get(r)?.push(i),this._vertices.get(i)?.push(r)}}catch{throw new f("Edge cannot be added because one of vertices was not found")}return this}removeEdge(t,e){try{const s=this.tryFindVertex(t),r=this.tryFindVertex(e),i=this.getEdgeByValue(s,r),n=this._vertices.get(s)||[],h=this._vertices.get(r)||[],a=n.filter(t=>r!==t),o=h.filter(t=>s!==t);this._vertices.set(s,a),this._vertices.set(r,o),this._edges=this._edges.filter(t=>t!==i)}catch{throw new f("Edge cannot be removed because one of vertices was not found")}return this}}const v=t=>{let e;switch(t){case g.DIRECTED:e=new E;break;case g.UNDIRECTED:e=new y}return e},N=1,I=0,V=(t,e,s)=>{if(!c(t))throw new h("Given array is not a matrix");const r=v(s);return e.forEach(t=>{r.addVertex(t)}),t.forEach((i,n)=>{i.forEach((i,h)=>{const a=t[n][h],o=t[h][n];s===g.UNDIRECTED&&1===a&&1===o&&r.addEdge(e[n],e[h]),s===g.DIRECTED&&(1===a&&r.addEdge(e[n],e[h]),1===o&&r.addEdge(e[h],e[n]))})}),r},R=t=>{const e=t.vertices(),s=new Array(t.verticesCount());return e.forEach((r,i)=>{s[i]=new Array(t.verticesCount()),e.forEach((e,n)=>{const h=t.hasEdge(r,e);s[i][n]=h?1:0})}),s},k=t=>{const e=t.vertices(),s=R(t),r=p(s);return V(r,e,g.DIRECTED)};class b extends h{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,b.prototype)}}class D extends _{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,D.prototype)}}class B extends _{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,B.prototype)}}class C extends h{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,C.prototype)}}class O{_capacity;_length;_head;_tail;constructor(t){this._capacity=O.calculateCapacity(t),this._head=null,this._tail=null,this._length=0}static calculateCapacity(t){if(void 0===t)return Number.MAX_VALUE;if(t<=0)throw new b("Capacity must be larger than 0");return t}insertNodeBetweenTwoNodes(t,e,s){if(this.isFull())throw new D("List is full, no more space available");null===this._head&&(this._head=t),null===this._tail&&(this._tail=t),e||(e=this._tail),s||(s=this._head),this.insertNodeBetweenTwoNodesImpl(t,e,s),this._length++}deleteNode(t){if(this.isEmpty())throw new B("cannot delete because list is empty");return this.deleteNodeImpl(t),this._length--,this.isEmpty()&&this.clear(),t}getNodeByIndex(t){const e=t<0||t>this._length;if(this.isEmpty())throw new B("List is empty");if(e)throw new C("Index exceed list length");let s=this._tail,r=0;for(;s&&r<t;)s=s.next,r++;return s}unshift(t){const e=this.createNode(t);this.insertNodeBetweenTwoNodes(e,this._head,this._tail),this._tail=e}push(t){const e=this.createNode(t);this.insertNodeBetweenTwoNodes(e,this._head,this._tail),this._head=e}pushFromIndex(t,e){const s=e<0||e>this._length,r=this.isEmpty()&&0===e;if(s)throw new C("index must be in range between 0 and list length");if(r)this.push(t);else{const s=this.createNode(t),r=this.getNodeByIndex(e-1),i=this.getNodeByIndex(e);this.insertNodeBetweenTwoNodes(s,r,i)}}pop(){const t=this.deleteNode(this._head);return this.popImpl(),t.data}shift(){const t=this.deleteNode(this._tail);return this.shiftImpl(),t.data}deleteFromIndex(t){const e=this.getNodeByIndex(t);return this.deleteNode(e).data}length(){return this._length}isEmpty(){return 0===this._length||null===this._head||null===this._tail}isFull(){return this._length>=this._capacity}has(t){return this.getAsArray().includes(t)}peek(){if(this.isEmpty()||!this._head)throw new B("head does not exist");return this._head.data}peekFromStart(){if(this.isEmpty()||!this._tail)throw new B("tail does not exist");return this._tail.data}peekByIndex(t){return this.getNodeByIndex(t).data}clear(){this._head=null,this._tail=null,this._length=0}getAsArray(){const t=[];let e=this._tail,s=0;for(;e&&s<this._length;)e&&t.push(e.data),e=e.next,s++;return t}pushFromArray(t){t.forEach(t=>{if(this.isFull())throw new D("List is full, no more space available");this.push(t)})}}class T{_next;_data;constructor(t,e=null){this._data=t,this._next=e}get data(){return this._data}get next(){return this._next}set next(t){this._next=t}}class F extends T{_prev;_next;constructor(t,e=null,s=null){super(t),this._prev=s,this._next=e}set prev(t){this._prev=t}get prev(){return this._prev}set next(t){this._next=t}get next(){return this._next}}class P extends O{_head;_tail;constructor(t){super(t),this._head=null,this._tail=null}createNode(t){return new F(t)}insertNodeBetweenTwoNodesImpl(t,e,s){t.next=s,t.prev=e,t.prev&&(t.prev.next=t),t.next&&(t.next.prev=t)}deleteNodeImpl(t){t.prev.next=t.next,t.next.prev=t.prev,t.next=null,t.prev=null}popImpl(){this._head=this._tail?.prev||null}shiftImpl(){this._tail=this._head?.next||null}reverse(){let t=this._tail,e=0;for(;t&&e<this._length;){const s=t.next,r=t.prev;t.prev=s,t.next=r,e++,t=r}t&&(this._tail=t.next,this._head=t)}}class S{_list;constructor(t){this._list=new P(t)}peek(){if(this.isEmpty())throw new B("Cannot peek when list is empty");return this._list.peek()}push(t){if(this._list.isFull())throw new D("Cannot push when queue is full");this._list.unshift(t)}pop(){if(this.isEmpty())throw new B("Cannot pop when list is empty");return this._list.pop()}has(t){return this._list.has(t)}isEmpty(){return this._list.isEmpty()}isFull(){return this._list.isFull()}clear(){this._list.clear()}length(){return this._list.length()}reverse(){this._list.reverse()}}class A{graph;visited;parents;constructor(t){this.graph=t,this.visited=/* @__PURE__ */new Map,this.parents=/* @__PURE__ */new Map}initIterator(t){if(!this.graph.hasVertex(t))throw new f("Start vertex does not exist");this.initIteratorImpl(t)}hasNext(){return this.hasNextImpl()}next(){if(!this.hasNext())throw new _("Next element does not exist");return this.nextImpl()}current(){try{return this.currentImpl()}catch(t){throw new _("Current element does not exist")}}getPath(t,e){const s=new Array,r=this.graph.hasEdge(t,e);let i=this.parents.get(e);if(r)return[t,e];for(;i&&i!==t;)s.push(i),i=this.parents.get(i);if(0===s.length)throw new _("There is no path found");return[t,...s.reverse(),e]}}class M extends A{queue;constructor(t){super(t),this.queue=new S}currentImpl(){return this.queue.peek()}initIteratorImpl(t){this.queue.push(t),this.visited.set(t,!0)}hasNextImpl(){return!this.queue.isEmpty()}nextImpl(){const t=this.queue.pop();return this.graph.getVertexNeighbors(t).forEach(e=>{!this.visited.get(e)&&(this.queue.push(e),this.visited.set(e,!0),this.parents.set(e,t))}),t}}class L{createIterator(t){return new M(t)}}class j{_list;constructor(t){this._list=new P(t)}peek(){if(this.isEmpty())throw new B("Cannot peek when list is empty");return this._list.peek()}push(t){if(this.isFull())throw new D("Stack is full");this._list.push(t)}pop(){if(this.isEmpty())throw new B("Cannot pop when stack is empty");return this._list.pop()}has(t){return this._list.has(t)}isEmpty(){return this._list.isEmpty()}isFull(){return this._list.isFull()}clear(){this._list.clear()}length(){return this._list.length()}reverse(){this._list.reverse()}}class U extends A{stack;constructor(t){super(t),this.stack=new j}hasNextImpl(){return!this.stack.isEmpty()}initIteratorImpl(t){this.stack.push(t),this.visited.set(t,!0)}currentImpl(){return this.stack.peek()}nextImpl(){const t=this.stack.pop();return this.graph.getVertexNeighbors(t).forEach(e=>{!this.visited.get(e)&&(this.stack.push(e),this.visited.set(e,!0),this.parents.set(e,t))}),t}}class q{createIterator(t){return new U(t)}}class H extends A{costs;constructor(t){super(t),this.costs=/* @__PURE__ */new Map}getClosestNotVisited(){const t=Array.from(this.costs.keys()).filter(t=>!this.visited.get(t)).sort((t,e)=>(this.costs.get(t)||0)-(this.costs.get(e)||0));if(void 0===t[0])throw new _("No more vertices found");return t[0]}initIteratorImpl(t){this.visited.set(t,!0),this.costs.set(t,0),this.graph.getVertexNeighbors(t).forEach(e=>{const s=this.graph.getEdgeWeight(t,e);this.costs.set(e,s),this.parents.set(e,t)})}hasNextImpl(){return!(null===this.getClosestNotVisited())}currentImpl(){return this.getClosestNotVisited()}nextImpl(){const t=this.getClosestNotVisited();this.visited.set(t,!0);const e=this.graph.getVertexNeighbors(t),s=this.costs.get(t);return e.forEach(e=>{const r=this.graph.getEdgeWeight(t,e),i=this.costs.get(e)||1/0,n=(s||0)+r;n<i&&(this.costs.set(e,n),this.parents.set(e,t))}),t}}class W{createIterator(t){return new H(t)}}const G=(t,e,s,r)=>{if(!t.hasVertex(e))throw new f("Start vertex was not found");if(!t.hasVertex(s))throw new f("End vertex was not found");const i=r.createIterator(t);for(i.initIterator(e);i.hasNext();){if(i.next()===s)return!0}return!1},Z=(t,e,s,r)=>{if(!t.hasVertex(e))throw new f("Start vertex was not found");if(!t.hasVertex(s))throw new f("End vertex was not found");const i=r.createIterator(t);for(i.initIterator(e);i.hasNext();){if(i.next()===s)break}return i.getPath(e,s)},z=t=>t.vertices().reduce((e,s)=>{const r=t.getVertexNeighbors(s);return e.set(s,r),e},/* @__PURE__ */new Map);var J=/* @__PURE__ */(t=>(t.NUMBERS="NUMBERS",t.HASH="HASH",t))(J||{});const X=()=>"_"+Math.random().toString(36).substr(2,9),$=(t,e,s=g.UNDIRECTED,r=J.NUMBERS)=>{const i=v(s),n=((t,e)=>{let s=e*(e-1);switch(t){case g.DIRECTED:break;case g.UNDIRECTED:s=Math.floor(s/2)}return s})(s,t);if(e<=0||e>n)throw new b(`Edges count must be in range between 0 and ${n}`);((t,e,s)=>{switch(e){case J.HASH:for(let e=0;e<s;e++)t.addVertex(X());break;case J.NUMBERS:for(let e=0;e<s;e++)t.addVertex((e+1).toString())}})(i,r,t);const h=i.vertices();let a=0;for(;a<e;){const t=()=>d(0,h.length),e=h[t()],s=h[t()],r=i.hasEdge(e,s);e===s||r||(i.addEdge(e,s),a++)}return i};var K=/* @__PURE__ */(t=>(t.DOUBLE="Double linked list",t.SINGLE="Single linked list",t))(K||{});class Q extends T{constructor(t,e=null){super(t,e)}}class Y extends O{_head;_tail;constructor(t){super(t),this._head=null,this._tail=null}getPrevNode(t){let e=this._tail;for(;e?.next!==t;)e=e?.next||null;return e}createNode(t){return new Q(t)}insertNodeBetweenTwoNodesImpl(t,e,s){t.next=s,e&&(e.next=t)}deleteNodeImpl(t){this.getPrevNode(t).next=t.next,t.next=null}popImpl(){this._head=this.getPrevNode(this._tail)}shiftImpl(){this._tail=this._head?.next||null}reverse(){let t=this._tail,e=this._head,s=0;for(;s<this._length;){const r=t?.next||null;t&&(t.next=e),s++,e=t,t=r}t&&(this._head=t,this._tail=t.next)}}class tt extends P{constructor(t){super(t)}iterator(t=0){const e=this._head,s=this._tail;let r=this.getNodeByIndex(t);const i={current:()=>r.data,hasNext:()=>Boolean(r.next)&&r!==e,hasPrev:()=>Boolean(r.prev)&&r!==s,next:()=>{if(!i.hasNext())throw new f("Next element does not exist");return r=r.next,r.data},prev:()=>{if(!i.hasPrev())throw new f("Prev element does not exist");return r=r.prev,r.data}};return i}}class et extends Y{constructor(t){super(t)}iterator(t=0){const e=this._head;let s=this.getNodeByIndex(t);const r={current:()=>s.data,hasNext:()=>Boolean(s.next)&&s!==e,next:()=>{if(!r.hasNext())throw new f("Next element does not exist");return s=s.next,s.data}};return r}}const st=(t,e=!1,s)=>{let r;if(e)switch(t){case K.DOUBLE:r=new tt(s);break;case K.SINGLE:r=new et(s)}else switch(t){case K.DOUBLE:r=new P(s);break;case K.SINGLE:r=new Y(s)}return r};var rt=/* @__PURE__ */(t=>(t.BST="Binary Search Tree",t.RANDOMIZED_BST="Randomized Binary Search Tree",t))(rt||{}),it=/* @__PURE__ */(t=>(t.IN_ORDER="IN_ORDER",t.PRE_ORDER="PRE_ORDER",t.POST_ORDER="POST_ORDER",t))(it||{});class nt{compare=(t,e)=>t>e;_head;_length;constructor(t){t&&(this.compare=t),this._head=null,this._length=0}length(){return this._length}}class ht{_data;_left;_right;_parent;constructor(t){this._data=t,this._left=null,this._right=null,this._parent=null}get data(){return this._data}set data(t){this._data=t}get left(){return this._left}set left(t){this._left=t}get right(){return this._right}set right(t){this._right=t}get parent(){return this._parent}set parent(t){this._parent=t}}class at extends ht{_left;_right;_parent;constructor(t){super(t),this._left=null,this._right=null,this._parent=null}get left(){return this._left}set left(t){this._left=t}get right(){return this._right}set right(t){this._right=t}get parent(){return this._parent}set parent(t){this._parent=t}}class ot extends nt{_head;constructor(t){super(t),this._head=null}checkIsEmpty(){if(null===this._head)throw new B("Tree is empty")}updateLeftRightParents(t){t.left&&t.left.parent!==t&&(t.left.parent=t),t.right&&t.right.parent!==t&&(t.right.parent=t)}findNode(t){let e=this._head;for(;e&&e.data!==t;)e=this.compare(e.data,t)?e.left:e.right;return e}insertToLeaf(t){let e=null,s=this._head;for(;s;)e=s,s=this.compare(s.data,t.data)?s.left:s.right;t.parent=e,null===e?this._head=t:this.compare(e.data,t.data)?e.left=t:e.right=t,this._length++}join(t,e){return null===t?e:null===e?t:(e.left=this.join(t,e.left),e.left&&this.updateLeftRightParents(e),e)}max(){this.checkIsEmpty();let t=this._head;for(;t?.right;)t=t.right;return t.data}min(){this.checkIsEmpty();let t=this._head;for(;t?.left;)t=t.left;return t.data}insert(t){if(this.has(t))throw new x("Node already exists");const e=new at(t);this.insertToLeaf(e)}has(t){const e=this.findNode(t);return e?.data===t}delete(t){if(!this.has(t))throw new f("Value does not exist in the tree");const e=(t,s)=>{if(null===t)return t;if(t.data===s){const e=this.join(t.left,t.right);return e&&(e.parent=t.parent),e}return this.compare(t.data,s)?t.left=e(t.left,s):t.right=e(t.right,s),this.updateLeftRightParents(t),t};this._head=e(this._head,t),this._length--}subtree(t){const e=new ot,s=this.findNode(t),r=new S,i=[];for(r.push(s);!r.isEmpty();){const t=r.pop();i.push(t),t?.left&&r.push(t.left),t?.right&&r.push(t.right)}return i.forEach(t=>{null!==t&&e.insert(t.data)}),e}traverse(t,e){this.checkIsEmpty();const s=new Array(this.length()),r=void 0!==e?this.findNode(e):this._head,i=t=>{null!==t&&(i(t.left),s.push(t.data),i(t.right))};switch(t){case it.IN_ORDER:i(r);break;case it.POST_ORDER:null!==(n=r)&&(i(n.left),i(n.right),s.push(n.data));break;case it.PRE_ORDER:(t=>{null!==t&&(s.push(t.data),i(t.left),i(t.right))})(r)}var n;return s.filter(t=>void 0!==t)}height(){const t=e=>{if(null===e)return 0;const s=null===e.left?-1:t(e.left),r=null===e.right?-1:t(e.right);return(s>r?s:r)+1};return null===this._head?0:t(this._head)+1}}class lt extends at{_rank;_left;_right;_parent;constructor(t){super(t),this._rank=0,this._left=null,this._right=null,this._parent=null}get rank(){return this._rank}set rank(t){this._rank=t}get left(){return this._left}set left(t){this._left=t}get right(){return this._right}set right(t){this._right=t}get parent(){return this._parent}set parent(t){this._parent=t}}class dt extends ot{_head;constructor(t){super(t),this._head=null}updateRank(t){t.rank=(t.right?.rank||0)+(t.left?.rank||0)+1}addCreatedNode(t,e=null){return t.rank=1,null!==e&&(t.parent=e),t}rotateNodeRight(t){const e=t.left;null!==e&&(t.left=e.right,null!==e.right&&(e.right.parent=t),e.parent=t.parent,null===t.parent?this._head=e:t===t.parent.right?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e,this.updateRank(t),this.updateRank(e))}rotateNodeLeft(t){const e=t.right;null!==e&&(t.right=e.left,null!==e.left&&(e.left.parent=t),e.parent=t.parent,null===t.parent?this._head=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e,this.updateRank(t),this.updateRank(e))}join(t,e){return null===t?e:null===e?t:Math.random()<t.rank/(t.rank+e.rank)?(t.right=this.join(t.right,e),t.right&&this.updateLeftRightParents(t),this.updateRank(t),t):(e.left=this.join(t,e.left),e.left&&this.updateLeftRightParents(e),this.updateRank(e),e)}updateLeftRightParents(t){super.updateLeftRightParents(t),this.updateRank(t)}insertToRoot(t,e){const s=e=>{this.compare(e.data,t.data)?(null===e.left?e.left=this.addCreatedNode(t,e):s(e.left),this.rotateNodeRight(e)):(null===e.right?e.right=this.addCreatedNode(t,e):s(e.right),this.rotateNodeLeft(e))};null===this._head?this._head=this.addCreatedNode(t):s(e||this._head)}insertRandomly(t){const e=s=>{Math.random()<1/(s.rank+1)?this.insertToRoot(t,s):(s.rank=s.rank+1,this.compare(s.data,t.data)?null===s.left?s.left=this.addCreatedNode(t,s):e(s.left):null===s.right?s.right=this.addCreatedNode(t,s):e(s.right))};null===this._head?this._head=this.addCreatedNode(t):e(this._head)}insert(t){if(this.has(t))throw new x("Node already exists");const e=new lt(t);this.insertRandomly(e)}delete(t){super.delete(t),this._length=this.length()}length(){return this._head?.rank||0}}const ut=t=>{let e;switch(t){case rt.BST:e=new ot;break;case rt.RANDOMIZED_BST:e=new dt}return e},ct=t=>{for(let e=0;e<t.length-1;e++)for(let s=0;s<t.length-1;s++)t[s]>t[s+1]&&l(t,s,s+1);return t},pt=t=>{for(let e=0;e<t.length;e++){const s=o(t,e);l(t,s,e)}return t},gt=(t,e,s)=>{if(s>e){const r=Math.floor(e+(s-e)/2);gt(t,e,r),gt(t,r+1,s),((t,e,s,r)=>{const i=t.slice(e,r+1);let n=e,h=e,a=s+1;for(;h<=s&&a<=r;){const s=i[h-e],r=i[a-e];s<r?(t[n]=s,h++):(t[n]=r,a++),n++}for(;h<=s;)t[n]=i[h-e],n++,h++;for(;a<=r;)t[n]=i[a-e],n++,a++})(t,e,r,s)}},_t=t=>(gt(t,0,t.length-1),t),ft=t=>{for(let e=1;e<t.length;e++){const s=t[e];let r=e-1;for(;r>=0&&t[r]>s;)l(t,r+1,r),r--;t[r+1]=s}return t},xt=t=>{const e=(t,s=0,r=t.length-1)=>{if(s<r){const i=((t,e,s)=>{const r=t[e];let i=e,n=s;for(;i<=n;){for(;t[n]>r;)n--;for(;t[i]<r;)i++;i<=n&&(l(t,i,n),n--,i++)}return i})(t,s,r);e(t,s,i-1),e(t,i,r)}return t};return e(t)};export{L as BFSIterationStrategy,ot as BinarySearchTree,B as CollectionIsEmptyException,D as CollectionIsFullException,q as DFSIterationStrategy,W as DijkstraIterationStrategy,E as DirectedGraph,P as DoubleLinkedList,N as EDGE_EXISTS_STATE,I as EDGE_NOT_EXISTS_STATE,M as GraphIteratorBFS,U as GraphIteratorDFS,H as GraphIteratorDijkstra,h as IllegalArgumentException,_ as IllegalStateException,C as IndexOutOfBoundsException,x as IsAlreadyExistsException,f as IsNotFoundException,tt as IterableDoubleLinkedList,et as IterableSingleLinkedList,S as Queue,dt as RandBinarySearchTree,Y as SingleLinkedList,j as Stack,y as UndirectedGraph,b as ValueOutOfRangeException,n as binarySearch,ct as bubbleSort,ut as createBinaryTree,v as createGraph,V as createGraphFromMatrix,st as createLinkedList,e as factorial,r as fibonacci,$ as generateRandomGraph,a as getMinIndex,o as getMinIndexFromIndex,G as hasPath,ft as insertionSort,t as memoize,s as memoizedFactorial,i as memoizedFibonacci,_t as mergeSort,z as presenterAdjacencyLists,R as presenterAdjacencyMatrix,xt as quickSort,d as randomizeNumberInRange,u as roundNumber,pt as selectSort,Z as shortestPath,l as swapArrayItems,k as transposeDirectedGraph,p as transposeMatrix};
1
+ const t=1,e=0,s=t=>{const e=/* @__PURE__ */new Map;return(...s)=>{const r=JSON.stringify(s);if(!e.has(r)){const i=t(...s);e.set(r,i)}return e.get(r)}},r=t=>t<0?0:t>1?t*r(t-1):1,i=s(t=>t<0?0:t>1?t*i(t-1):1),h=t=>t>1?h(t-1)+h(t-2):t,n=s(t=>t>1?n(t-1)+n(t-2):t),a=(t,e)=>{let s=0,r=t.length-1;for(;s<=r;){const i=Math.floor(s+(r-s)/2),h=t[i];if(e===h)return i;h>e?r=i-1:s=i+1}return null};class o extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,o.prototype)}}const l=t=>{if(0===t.length)return!1;const e=t[0].length;for(let s=0;s<t.length;s++)if(t[s].length!==e)return!1;return!0},u=t=>{if(!l(t))throw new o("Given array is not a matrix");const e=t.length,s=t[0]?.length||0,r=[];for(let i=0;i<s;i++){r[i]=[];for(let s=0;s<e;s++)r[i][s]=t[s][i]}return r};var d=/* @__PURE__ */(t=>(t.DIRECTED="DIRECTED",t.UNDIRECTED="UNDIRECTED",t))(d||{});class c extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,c.prototype)}}class p extends c{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,p.prototype)}}class g extends c{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,g.prototype)}}class _{_vertices;_edges;constructor(){this._vertices=/* @__PURE__ */new Map,this._edges=/* @__PURE__ */new Map}static EDGE_KEY_SEPARATOR="_";getEdgeKey(t,e){return`${t}${_.EDGE_KEY_SEPARATOR}${e}`}getVerticesArrayFormat(){return Array.from(this._vertices.keys())}tryFindVertex(t){if(!this._vertices.has(t))throw new p("Vertex not found");return t}updateEdgeWeight(t,e,s){this.getEdgeByValue(t,e).weight=s}cascadeRemoveVertexRelations(t){const e=this._vertices.get(t);e&&e.forEach(e=>{this._vertices.get(e)?.delete(t),this._edges.delete(this.getEdgeKey(e,t))})}cascadeRemoveVertexEdges(t){for(const[e,s]of this._edges.entries())s.fromVertex!==t&&s.toVertex!==t||this._edges.delete(e)}weight(){let t=0;for(const e of this._edges.values())t+=e.weight;return t}vertices(){return this.getVerticesArrayFormat().map(t=>t)}verticesCount(){return this._vertices.size}edgesCount(){return this._edges.size}addVertex(t){if(this.hasVertex(t))throw new g("Vertex is already exist");return this._vertices.set(t,/* @__PURE__ */new Set),this}removeVertex(t){try{const e=this.tryFindVertex(t);this.cascadeRemoveVertexEdges(e),this.cascadeRemoveVertexRelations(e),this._vertices.delete(e)}catch{throw new p("Vertex does not exist already")}return this}getVertexNeighbors(t){const e=this.tryFindVertex(t),s=this._vertices.get(e);return s?Array.from(s):[]}hasVertex(t){return this._vertices.has(t)}hasEdge(t,e){return this._edges.has(this.getEdgeKey(t,e))}getEdgeWeight(t,e){const s=this.tryFindVertex(t),r=this.tryFindVertex(e);return this.getEdgeByValue(s,r).weight}*[Symbol.iterator](){yield*this._vertices.keys()}}class f{_fromVertex;_toVertex;_weight;constructor(t,e,s=0){this._fromVertex=t,this._toVertex=e,this._weight=s}get fromVertex(){return this._fromVertex}get toVertex(){return this._toVertex}get weight(){return this._weight}set weight(t){this._weight=t}}class x extends _{constructor(){super()}getEdgeByValue(t,e){const s=this.getEdgeKey(t,e),r=this._edges.get(s);if(!r)throw new p("Edge was not found");return r}addEdge(t,e,s){try{const r=this.tryFindVertex(t),i=this.tryFindVertex(e),h=this.getEdgeKey(r,i);if(this.hasEdge(r,i))"number"==typeof s&&this.updateEdgeWeight(r,i,s);else{const t=new f(r,i,s);this._edges.set(h,t),this._vertices.get(r)?.add(i)}}catch{throw new p("Edge cannot be added because one of vertices was not found")}return this}removeEdge(t,e){const s=this.tryFindVertex(t),r=this.tryFindVertex(e),i=this.getEdgeKey(s,r);if(!this._edges.has(i))throw new p("Edge cannot be removed because edge was not found");return this._vertices.get(s)?.delete(r),this._edges.delete(i),this}removeVertex(t){const e=this.tryFindVertex(t);for(const[s,r]of this._edges.entries())r.fromVertex!==e&&r.toVertex!==e||this._edges.delete(s);return this._vertices.forEach(t=>{t.delete(e)}),this._vertices.delete(e),this}}class w extends _{constructor(){super()}getEdgeKey(t,e){return this instanceof w?[t,e].sort().join(w.EDGE_KEY_SEPARATOR):`${t}${w.EDGE_KEY_SEPARATOR}${e}`}getEdgeByValue(t,e){const s=this.getEdgeKey(t,e),r=this._edges.get(s);if(!r)throw new p("Edge not found");return r}hasEdge(t,e){return this._edges.has(this.getEdgeKey(t,e))}addEdge(t,e,s){try{const r=this.tryFindVertex(t),i=this.tryFindVertex(e),h=this.getEdgeKey(r,i);if(this.hasEdge(r,i))"number"==typeof s&&this.updateEdgeWeight(r,i,s);else{const t=new f(r,i,s);this._edges.set(h,t),this._vertices.get(r)?.add(i),this._vertices.get(i)?.add(r)}}catch{throw new p("Edge cannot be added because one of vertices was not found")}return this}removeEdge(t,e){const s=this.tryFindVertex(t),r=this.tryFindVertex(e),i=this.getEdgeKey(s,r);if(!this.hasEdge(s,r))throw new p("Edge cannot be removed because edge was not found");return this._edges.delete(i),this._vertices.get(s)?.delete(r),this._vertices.get(r)?.delete(s),this}}const m=t=>{let e;switch(t){case d.DIRECTED:e=new x;break;case d.UNDIRECTED:e=new w}return e},y=(t,e,s)=>{if(!(l(t)&&t.length===t[0]?.length&&t.length===e.length))throw new o("Given array is not a matrix");const r=m(s);return e.forEach(t=>r.addVertex(t)),t.forEach((t,i)=>{t.forEach((t,h)=>{if(1===t){const t=e[i],n=e[h];s===d.UNDIRECTED&&(r.hasEdge(t,n)||r.hasEdge(n,t))||r.addEdge(t,n)}})}),r},E=t=>{const e=t.vertices(),s=new Array(t.verticesCount());return e.forEach((r,i)=>{s[i]=new Array(t.verticesCount()),e.forEach((e,h)=>{const n=t.hasEdge(r,e);s[i][h]=n?1:0})}),s},v=t=>{const e=t.vertices(),s=E(t),r=u(s);return y(r,e,d.DIRECTED)};class N extends o{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,N.prototype)}}class I extends c{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,I.prototype)}}class R extends c{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,R.prototype)}}class k extends o{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,k.prototype)}}class V{_capacity;_length;_head;_tail;constructor(t){this._capacity=V.calculateCapacity(t),this._head=null,this._tail=null,this._length=0}static calculateCapacity(t){if(void 0===t)return Number.MAX_VALUE;if(t<=0)throw new N("Capacity must be larger than 0");return t}insertNodeBetweenTwoNodes(t,e,s){if(this.isFull())throw new I("List is full, no more space available");null===this._head&&(this._head=t),null===this._tail&&(this._tail=t),e||(e=this._tail),s||(s=this._head),this.insertNodeBetweenTwoNodesImpl(t,e,s),this._length++}deleteNode(t){if(null===t||this.isEmpty())throw new R("cannot delete because list is empty");return this.deleteNodeImpl(t),this._length--,this.isEmpty()&&this.clear(),t}getNodeByIndex(t){const e=t<0||t>this._length;if(this.isEmpty())throw new R("List is empty");if(e)throw new k("Index exceed list length");let s=this._tail,r=0;for(;s&&r<t;)s=s.next,r++;return s}unshift(t){const e=this.createNode(t);this.insertNodeBetweenTwoNodes(e,this._head,this._tail),this._tail=e}push(t){const e=this.createNode(t);this.insertNodeBetweenTwoNodes(e,this._head,this._tail),this._head=e}pushFromIndex(t,e){const s=e<0||e>this._length,r=this.isEmpty()&&0===e;if(s)throw new k("index must be in range between 0 and list length");if(r)this.push(t);else{const s=this.createNode(t),r=this.getNodeByIndex(e-1),i=this.getNodeByIndex(e);this.insertNodeBetweenTwoNodes(s,r,i)}}pop(){const t=this.deleteNode(this._head);return this.popImpl(),t.data}shift(){const t=this.deleteNode(this._tail);return this.shiftImpl(),t.data}deleteFromIndex(t){const e=this.getNodeByIndex(t);return this.deleteNode(e).data}length(){return this._length}isEmpty(){return 0===this._length||null===this._head||null===this._tail}isFull(){return this._length>=this._capacity}has(t){return this.getAsArray().includes(t)}peek(){if(this.isEmpty()||!this._head)throw new R("head does not exist");return this._head.data}peekFromStart(){if(this.isEmpty()||!this._tail)throw new R("tail does not exist");return this._tail.data}peekByIndex(t){return this.getNodeByIndex(t).data}clear(){this._head=null,this._tail=null,this._length=0}getAsArray(){const t=[];let e=this._tail,s=0;for(;e&&s<this._length;)e&&t.push(e.data),e=e.next,s++;return t}pushFromArray(t){t.forEach(t=>{if(this.isFull())throw new I("List is full, no more space available");this.push(t)})}*[Symbol.iterator](){let t=this._tail;for(;t;)yield t.data,t=t.next}}class b{_next;_data;constructor(t,e=null){this._data=t,this._next=e}get data(){return this._data}get next(){return this._next}set next(t){this._next=t}}class O extends b{_prev;_next;constructor(t,e=null,s=null){super(t),this._prev=s,this._next=e}set prev(t){this._prev=t}get prev(){return this._prev}set next(t){this._next=t}get next(){return this._next}}class D extends V{_head;_tail;constructor(t){super(t),this._head=null,this._tail=null}createNode(t){return new O(t)}insertNodeBetweenTwoNodesImpl(t,e,s){t.next=s,t.prev=e,t.prev&&(t.prev.next=t),t.next&&(t.next.prev=t)}deleteNodeImpl(t){t.prev&&(t.prev.next=t.next),t.next&&(t.next.prev=t.prev),t.next=null,t.prev=null}popImpl(){this._head=this._tail?.prev||null}shiftImpl(){this._tail=this._head?.next||null}reverse(){let t=this._tail,e=0;for(;t&&e<this._length;){const s=t.next,r=t.prev;t.prev=s,t.next=r,e++,t=r}t&&(this._tail=t.next,this._head=t)}}class P{_list;constructor(t){this._list=new D(t)}peek(){if(this.isEmpty())throw new R("Cannot peek when list is empty");return this._list.peek()}push(t){if(this._list.isFull())throw new I("Cannot push when queue is full");this._list.unshift(t)}pop(){if(this.isEmpty())throw new R("Cannot pop when list is empty");return this._list.pop()}has(t){return this._list.has(t)}isEmpty(){return this._list.isEmpty()}isFull(){return this._list.isFull()}clear(){this._list.clear()}length(){return this._list.length()}reverse(){this._list.reverse()}}class T{graph;visited;parents;constructor(t){this.graph=t,this.visited=/* @__PURE__ */new Map,this.parents=/* @__PURE__ */new Map}initIterator(t){if(!this.graph.hasVertex(t))throw new p("Start vertex does not exist");this.initIteratorImpl(t)}hasNext(){return this.hasNextImpl()}next(){if(!this.hasNext())throw new c("Next element does not exist");return this.nextImpl()}current(){try{return this.currentImpl()}catch(t){throw new c("Current element does not exist")}}getPath(t,e){const s=new Array,r=this.graph.hasEdge(t,e);let i=this.parents.get(e);if(r)return[t,e];for(;i&&i!==t;)s.push(i),i=this.parents.get(i);if(0===s.length)throw new c("There is no path found");return[t,...s.reverse(),e]}}class C extends T{queue;constructor(t){super(t),this.queue=new P}currentImpl(){return this.queue.peek()}initIteratorImpl(t){this.queue.push(t),this.visited.set(t,!0)}hasNextImpl(){return!this.queue.isEmpty()}nextImpl(){const t=this.queue.pop();return this.graph.getVertexNeighbors(t).forEach(e=>{!this.visited.get(e)&&(this.queue.push(e),this.visited.set(e,!0),this.parents.set(e,t))}),t}}class B{_items=[];_capacity;constructor(t){this._capacity=t}length(){return this._items.length}isEmpty(){return 0===this._items.length}isFull(){return void 0!==this._capacity&&this._items.length===this._capacity}peek(){if(this.isEmpty())throw new R("Cannot peek when list is empty");return this._items[this._items.length-1]}push(t){if(this.isFull())throw new I("Stack is full");this._items.push(t)}pop(){if(this.isEmpty())throw new R("Cannot pop when stack is empty");return this._items.pop()}has(t){return this._items.includes(t)}clear(){this._items.length=0}reverse(){this._items.reverse()}*[Symbol.iterator](){yield*this._items}}class S extends T{stack;constructor(t){super(t),this.stack=new B}hasNextImpl(){return!this.stack.isEmpty()}initIteratorImpl(t){this.stack.push(t),this.visited.set(t,!0)}currentImpl(){return this.stack.peek()}nextImpl(){const t=this.stack.pop();return this.graph.getVertexNeighbors(t).forEach(e=>{!this.visited.get(e)&&(this.stack.push(e),this.visited.set(e,!0),this.parents.set(e,t))}),t}}class F{_heap=[];_comparator;constructor(t){this._comparator=t||this.defaultComparator}get size(){return this._heap.length}isEmpty(){return 0===this.size}peek(){if(this.isEmpty())throw new R("Cannot peek when heap is empty");return this._heap[0]}insert(t){this._heap.push(t),this.bubbleUp()}extractMin(){if(this.isEmpty())throw new R("Cannot extract from an empty heap");const t=this._heap[0],e=this._heap.pop();return this.isEmpty()||(this._heap[0]=e,this.bubbleDown()),t}defaultComparator(t,e){return t<e?-1:t>e?1:0}parentIndex(t){return Math.floor((t-1)/2)}leftChildIndex(t){return 2*t+1}rightChildIndex(t){return 2*t+2}swap(t,e){[this._heap[t],this._heap[e]]=[this._heap[e],this._heap[t]]}bubbleUp(){let t=this.size-1,e=this.parentIndex(t);for(;t>0&&this._comparator(this._heap[t],this._heap[e])<0;)this.swap(t,e),t=e,e=this.parentIndex(t)}bubbleDown(){let t=0;for(;;){const e=this.leftChildIndex(t),s=this.rightChildIndex(t);let r=t;if(e<this.size&&this._comparator(this._heap[e],this._heap[r])<0&&(r=e),s<this.size&&this._comparator(this._heap[s],this._heap[r])<0&&(r=s),r===t)break;this.swap(t,r),t=r}}*[Symbol.iterator](){yield*this._heap}}class q{_heap;constructor(){this._heap=new F((t,e)=>t.priority-e.priority)}get size(){return this._heap.size}isEmpty(){return this._heap.isEmpty()}enqueue(t,e){this._heap.insert({value:t,priority:e})}dequeue(){return this._heap.extractMin().value}peek(){return this._heap.peek().value}clear(){for(;!this.isEmpty();)this.dequeue()}}class A extends T{costs;queue;constructor(t){super(t),this.costs=/* @__PURE__ */new Map,this.queue=new q}initIteratorImpl(t){this.costs.set(t,0),this.queue.enqueue(t,0)}hasNextImpl(){return this.refreshQueue(),!this.queue.isEmpty()}currentImpl(){if(this.refreshQueue(),this.queue.isEmpty())throw new c("No more vertices found");return this.queue.peek()}nextImpl(){if(this.refreshQueue(),this.queue.isEmpty())throw new c("No more vertices found");const t=this.queue.dequeue();this.visited.set(t,!0);const e=this.graph.getVertexNeighbors(t),s=this.costs.get(t)??0;for(const r of e){if(this.visited.get(r))continue;const e=s+this.graph.getEdgeWeight(t,r);e<(this.costs.get(r)??1/0)&&(this.costs.set(r,e),this.parents.set(r,t),this.queue.enqueue(r,e))}return t}refreshQueue(){for(;!this.queue.isEmpty()&&this.visited.get(this.queue.peek());)this.queue.dequeue()}}var L=/* @__PURE__ */(t=>(t.BFS="Breadth first traversal",t.DFS="Deep first traversal",t.DIJKSTRA="Dijkstra traversal",t))(L||{});const M=(t,e)=>{switch(e){case L.BFS:return new C(t);case L.DFS:return new S(t);case L.DIJKSTRA:return new A(t);default:throw new o(`Unknown traversal mode: ${e}`)}},K=({graph:t,traversalType:e,from:s,to:r})=>{if(!t.hasVertex(s))throw new p("Start vertex was not found");if(!t.hasVertex(r))throw new p("End vertex was not found");const i=M(t,e);for(i.initIterator(s);i.hasNext();){if(i.next()===r)return!0}return!1},j=({graph:t,traversalType:e,from:s,to:r})=>{if(!t.hasVertex(s))throw new p("Start vertex was not found");if(!t.hasVertex(r))throw new p("End vertex was not found");const i=M(t,e);for(i.initIterator(s);i.hasNext();){if(i.next()===r)break}return i.getPath(s,r)},U=t=>t.vertices().reduce((e,s)=>{const r=t.getVertexNeighbors(s);return e.set(s,r),e},/* @__PURE__ */new Map);var z=/* @__PURE__ */(t=>(t.DOUBLE="Double linked list",t.SINGLE="Single linked list",t))(z||{});class G extends b{constructor(t,e=null){super(t,e)}}class $ extends V{_head;_tail;constructor(t){super(t),this._head=null,this._tail=null}getPrevNode(t){let e=this._tail;for(;e?.next!==t;)e=e?.next||null;return e}createNode(t){return new G(t)}insertNodeBetweenTwoNodesImpl(t,e,s){t.next=s,e&&(e.next=t)}deleteNodeImpl(t){const e=this.getPrevNode(t);e&&(e.next=t.next),t.next=null}popImpl(){this._head=this.getPrevNode(this._tail)}shiftImpl(){this._tail=this._head?.next||null}reverse(){let t=this._tail,e=this._head,s=0;for(;s<this._length;){const r=t?.next||null;t&&(t.next=e),s++,e=t,t=r}t&&(this._head=t,this._tail=t.next)}}class W extends D{constructor(t){super(t)}iterator(t=0){const e=this._head,s=this._tail;let r=this.getNodeByIndex(t);const i={current:()=>r.data,hasNext:()=>Boolean(r.next)&&r!==e,hasPrev:()=>Boolean(r.prev)&&r!==s,next:()=>{if(!i.hasNext())throw new p("Next element does not exist");return r=r.next,r.data},prev:()=>{if(!i.hasPrev())throw new p("Prev element does not exist");return r=r.prev,r.data}};return i}}class Q extends ${constructor(t){super(t)}iterator(t=0){const e=this._head;let s=this.getNodeByIndex(t);const r={current:()=>s.data,hasNext:()=>Boolean(s.next)&&s!==e,next:()=>{if(!r.hasNext())throw new p("Next element does not exist");return s=s.next,s.data}};return r}}const Y=(t,e=!1,s)=>{let r;if(e)switch(t){case z.DOUBLE:r=new W(s);break;case z.SINGLE:r=new Q(s)}else switch(t){case z.DOUBLE:r=new D(s);break;case z.SINGLE:r=new $(s)}return r};var J=/* @__PURE__ */(t=>(t.BST="Binary Search Tree",t.RANDOMIZED_BST="Randomized Binary Search Tree",t))(J||{}),Z=/* @__PURE__ */(t=>(t.IN_ORDER="IN_ORDER",t.PRE_ORDER="PRE_ORDER",t.POST_ORDER="POST_ORDER",t))(Z||{});class X{compare=(t,e)=>t>e;_head;_length;constructor(t){t&&(this.compare=t),this._head=null,this._length=0}length(){return this._length}}class H{_data;_left;_right;_parent;constructor(t){this._data=t,this._left=null,this._right=null,this._parent=null}get data(){return this._data}set data(t){this._data=t}get left(){return this._left}set left(t){this._left=t}get right(){return this._right}set right(t){this._right=t}get parent(){return this._parent}set parent(t){this._parent=t}}class tt extends H{_left;_right;_parent;constructor(t){super(t),this._left=null,this._right=null,this._parent=null}get left(){return this._left}set left(t){this._left=t}get right(){return this._right}set right(t){this._right=t}get parent(){return this._parent}set parent(t){this._parent=t}}class et extends X{_head;constructor(t){super(t),this._head=null}checkIsEmpty(){if(null===this._head)throw new R("Tree is empty")}updateLeftRightParents(t){t.left&&t.left.parent!==t&&(t.left.parent=t),t.right&&t.right.parent!==t&&(t.right.parent=t)}findNode(t){let e=this._head;for(;e&&e.data!==t;)e=this.compare(e.data,t)?e.left:e.right;return e}insertToLeaf(t){let e=null,s=this._head;for(;s;)e=s,s=this.compare(s.data,t.data)?s.left:s.right;t.parent=e,null===e?this._head=t:this.compare(e.data,t.data)?e.left=t:e.right=t,this._length++}join(t,e){return null===t?e:null===e?t:(e.left=this.join(t,e.left),e.left&&this.updateLeftRightParents(e),e)}max(){this.checkIsEmpty();let t=this._head;for(;t?.right;)t=t.right;return t.data}min(){this.checkIsEmpty();let t=this._head;for(;t?.left;)t=t.left;return t.data}insert(t){if(this.has(t))throw new g("Node already exists");const e=new tt(t);this.insertToLeaf(e)}has(t){const e=this.findNode(t);return e?.data===t}delete(t){if(!this.has(t))throw new p("Value does not exist in the tree");const e=(t,s)=>{if(null===t)return t;if(t.data===s){const e=this.join(t.left,t.right);return e&&(e.parent=t.parent),e}return this.compare(t.data,s)?t.left=e(t.left,s):t.right=e(t.right,s),this.updateLeftRightParents(t),t};this._head=e(this._head,t),this._length--}subtree(t){const e=new et,s=this.findNode(t),r=new P,i=[];for(r.push(s);!r.isEmpty();){const t=r.pop();i.push(t),t?.left&&r.push(t.left),t?.right&&r.push(t.right)}return i.forEach(t=>{null!==t&&e.insert(t.data)}),e}traverse(t,e){this.checkIsEmpty();const s=[],r=void 0!==e?this.findNode(e):this._head;switch(t){case Z.IN_ORDER:this.storeInOrder(r,s);break;case Z.PRE_ORDER:this.storePreOrder(r,s);break;case Z.POST_ORDER:this.storePostOrder(r,s)}return s}storeInOrder(t,e){t&&(this.storeInOrder(t.left,e),e.push(t.data),this.storeInOrder(t.right,e))}storePreOrder(t,e){t&&(e.push(t.data),this.storePreOrder(t.left,e),this.storePreOrder(t.right,e))}storePostOrder(t,e){t&&(this.storePostOrder(t.left,e),this.storePostOrder(t.right,e),e.push(t.data))}height(){const t=e=>{if(null===e)return 0;const s=null===e.left?-1:t(e.left),r=null===e.right?-1:t(e.right);return(s>r?s:r)+1};return null===this._head?0:t(this._head)+1}}class st extends tt{_rank;_left;_right;_parent;constructor(t){super(t),this._rank=0,this._left=null,this._right=null,this._parent=null}get rank(){return this._rank}set rank(t){this._rank=t}get left(){return this._left}set left(t){this._left=t}get right(){return this._right}set right(t){this._right=t}get parent(){return this._parent}set parent(t){this._parent=t}}class rt extends et{_head;constructor(t){super(t),this._head=null}updateRank(t){t.rank=(t.right?.rank||0)+(t.left?.rank||0)+1}addCreatedNode(t,e=null){return t.rank=1,null!==e&&(t.parent=e),t}rotateNodeRight(t){const e=t.left;null!==e&&(t.left=e.right,null!==e.right&&(e.right.parent=t),e.parent=t.parent,null===t.parent?this._head=e:t===t.parent.right?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e,this.updateRank(t),this.updateRank(e))}rotateNodeLeft(t){const e=t.right;null!==e&&(t.right=e.left,null!==e.left&&(e.left.parent=t),e.parent=t.parent,null===t.parent?this._head=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e,this.updateRank(t),this.updateRank(e))}join(t,e){return null===t?e:null===e?t:Math.random()<t.rank/(t.rank+e.rank)?(t.right=this.join(t.right,e),t.right&&this.updateLeftRightParents(t),this.updateRank(t),t):(e.left=this.join(t,e.left),e.left&&this.updateLeftRightParents(e),this.updateRank(e),e)}updateLeftRightParents(t){super.updateLeftRightParents(t),this.updateRank(t)}insertToRoot(t,e){const s=e=>{this.compare(e.data,t.data)?(null===e.left?e.left=this.addCreatedNode(t,e):s(e.left),this.rotateNodeRight(e)):(null===e.right?e.right=this.addCreatedNode(t,e):s(e.right),this.rotateNodeLeft(e))};null===this._head?this._head=this.addCreatedNode(t):s(e||this._head)}insertRandomly(t){const e=s=>{Math.random()<1/(s.rank+1)?this.insertToRoot(t,s):(s.rank=s.rank+1,this.compare(s.data,t.data)?null===s.left?s.left=this.addCreatedNode(t,s):e(s.left):null===s.right?s.right=this.addCreatedNode(t,s):e(s.right))};null===this._head?this._head=this.addCreatedNode(t):e(this._head)}insert(t){if(this.has(t))throw new g("Node already exists");const e=new st(t);this.insertRandomly(e)}delete(t){super.delete(t),this._length=this.length()}length(){return this._head?.rank||0}}const it=t=>{let e;switch(t){case J.BST:e=new et;break;case J.RANDOMIZED_BST:e=new rt}return e},ht=(t,e,s)=>{if(e!==s){const r=t[e];t[e]=t[s],t[s]=r}},nt=t=>{for(let e=0;e<t.length-1;e++)for(let s=0;s<t.length-1;s++)t[s]>t[s+1]&&ht(t,s,s+1);return t},at=t=>t.reduce((e,s,r)=>s<t[e]?r:e,0),ot=(t,e)=>e+at(t.slice(e)),lt=t=>{for(let e=0;e<t.length;e++){const s=ot(t,e);ht(t,s,e)}return t},ut=(t,e,s)=>{if(s>e){const r=Math.floor(e+(s-e)/2);ut(t,e,r),ut(t,r+1,s),((t,e,s,r)=>{const i=t.slice(e,r+1);let h=e,n=e,a=s+1;for(;n<=s&&a<=r;){const s=i[n-e],r=i[a-e];s<r?(t[h]=s,n++):(t[h]=r,a++),h++}for(;n<=s;)t[h]=i[n-e],h++,n++;for(;a<=r;)t[h]=i[a-e],h++,a++})(t,e,r,s)}},dt=t=>(ut(t,0,t.length-1),t),ct=t=>{for(let e=1;e<t.length;e++){const s=t[e];let r=e-1;for(;r>=0&&t[r]>s;)ht(t,r+1,r),r--;t[r+1]=s}return t},pt=t=>{const e=(t,s=0,r=t.length-1)=>{if(s<r){const i=((t,e,s)=>{const r=t[e];let i=e,h=s;for(;i<=h;){for(;t[h]>r;)h--;for(;t[i]<r;)i++;i<=h&&(ht(t,i,h),h--,i++)}return i})(t,s,r);e(t,s,i-1),e(t,i,r)}return t};return e(t)},gt=(t,e=3)=>Math.round(t*10**e)/10**e,_t=(t,e)=>Math.floor(Math.random()*(e-t))+t;export{F as BinaryHeap,et as BinarySearchTree,R as CollectionIsEmptyException,I as CollectionIsFullException,x as DirectedGraph,D as DoubleLinkedList,t as EDGE_EXISTS_STATE,e as EDGE_NOT_EXISTS_STATE,C as GraphIteratorBFS,S as GraphIteratorDFS,A as GraphIteratorDijkstra,o as IllegalArgumentException,c as IllegalStateException,k as IndexOutOfBoundsException,g as IsAlreadyExistsException,p as IsNotFoundException,W as IterableDoubleLinkedList,Q as IterableSingleLinkedList,q as PriorityQueue,P as Queue,rt as RandBinarySearchTree,$ as SingleLinkedList,B as Stack,w as UndirectedGraph,N as ValueOutOfRangeException,a as binarySearch,nt as bubbleSort,it as createBinaryTree,m as createGraph,y as createGraphFromMatrix,M as createGraphIterator,Y as createLinkedList,r as factorial,h as fibonacci,at as getMinIndex,ot as getMinIndexFromIndex,K as hasPath,ct as insertionSort,s as memoize,i as memoizedFactorial,n as memoizedFibonacci,dt as mergeSort,U as presenterAdjacencyLists,E as presenterAdjacencyMatrix,pt as quickSort,_t as randomizeNumberInRange,gt as roundNumber,lt as selectSort,j as shortestPath,ht as swapArrayItems,v as transposeDirectedGraph,u as transposeMatrix};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@raikuxq/alg-ds",
3
3
  "scripts": {
4
4
  "test": "jest",
5
- "dev": "nodemon",
5
+ "dev": "nodemon --exec tsx src/index.ts",
6
6
  "build:lib": "rimraf ./lib && vite build",
7
7
  "build:dts": "dts-bundle-generator -o lib/index.d.ts src/index.ts --no-check --inline-declare-externals false --external-inlines @babel/types",
8
8
  "build:full": "yarn build:lib && yarn build:dts",
@@ -69,10 +69,11 @@
69
69
  "ts-node": "^10.9.2",
70
70
  "ts-node-esm": "^0.0.6",
71
71
  "typescript": "5.8.2",
72
+ "typescript-eslint": "^8.54.0",
72
73
  "vite": "^7.3.1",
73
74
  "vuepress": "^2.0.0-beta.48"
74
75
  },
75
76
  "dependencies": {},
76
- "version": "2.0.0",
77
+ "version": "3.0.0",
77
78
  "sideEffects": false
78
79
  }