data-structure-typed 2.0.0 → 2.0.1
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 +1 -1
- package/dist/cjs/data-structures/graph/abstract-graph.js +14 -14
- package/dist/cjs/data-structures/graph/abstract-graph.js.map +1 -1
- package/dist/cjs/data-structures/hash/hash-map.d.ts +46 -0
- package/dist/cjs/data-structures/hash/hash-map.js +46 -0
- package/dist/cjs/data-structures/hash/hash-map.js.map +1 -1
- package/dist/cjs/data-structures/linked-list/singly-linked-list.d.ts +66 -0
- package/dist/cjs/data-structures/linked-list/singly-linked-list.js +66 -0
- package/dist/cjs/data-structures/linked-list/singly-linked-list.js.map +1 -1
- package/dist/cjs/data-structures/queue/queue.d.ts +47 -0
- package/dist/cjs/data-structures/queue/queue.js +47 -0
- package/dist/cjs/data-structures/queue/queue.js.map +1 -1
- package/dist/cjs/data-structures/stack/stack.d.ts +121 -0
- package/dist/cjs/data-structures/stack/stack.js +121 -0
- package/dist/cjs/data-structures/stack/stack.js.map +1 -1
- package/dist/esm/data-structures/graph/abstract-graph.js +14 -14
- package/dist/esm/data-structures/graph/abstract-graph.js.map +1 -1
- package/dist/esm/data-structures/hash/hash-map.d.ts +46 -0
- package/dist/esm/data-structures/hash/hash-map.js +46 -0
- package/dist/esm/data-structures/hash/hash-map.js.map +1 -1
- package/dist/esm/data-structures/linked-list/singly-linked-list.d.ts +66 -0
- package/dist/esm/data-structures/linked-list/singly-linked-list.js +66 -0
- package/dist/esm/data-structures/linked-list/singly-linked-list.js.map +1 -1
- package/dist/esm/data-structures/queue/queue.d.ts +47 -0
- package/dist/esm/data-structures/queue/queue.js +47 -0
- package/dist/esm/data-structures/queue/queue.js.map +1 -1
- package/dist/esm/data-structures/stack/stack.d.ts +121 -0
- package/dist/esm/data-structures/stack/stack.js +121 -0
- package/dist/esm/data-structures/stack/stack.js.map +1 -1
- package/dist/individuals/binary-tree/avl-tree-counter.mjs +4701 -0
- package/dist/individuals/binary-tree/avl-tree-multi-map.mjs +4514 -0
- package/dist/individuals/binary-tree/avl-tree.mjs +4321 -0
- package/dist/individuals/binary-tree/binary-tree.mjs +3097 -0
- package/dist/individuals/binary-tree/bst.mjs +3858 -0
- package/dist/individuals/binary-tree/red-black-tree.mjs +4391 -0
- package/dist/individuals/binary-tree/tree-counter.mjs +4806 -0
- package/dist/individuals/binary-tree/tree-multi-map.mjs +4582 -0
- package/dist/individuals/graph/directed-graph.mjs +2910 -0
- package/dist/individuals/graph/undirected-graph.mjs +2745 -0
- package/dist/individuals/hash/hash-map.mjs +1040 -0
- package/dist/individuals/heap/heap.mjs +909 -0
- package/dist/individuals/heap/max-heap.mjs +671 -0
- package/dist/individuals/heap/min-heap.mjs +659 -0
- package/dist/individuals/linked-list/doubly-linked-list.mjs +1495 -0
- package/dist/individuals/linked-list/singly-linked-list.mjs +1479 -0
- package/dist/individuals/priority-queue/max-priority-queue.mjs +768 -0
- package/dist/individuals/priority-queue/min-priority-queue.mjs +757 -0
- package/dist/individuals/priority-queue/priority-queue.mjs +670 -0
- package/dist/individuals/queue/deque.mjs +1262 -0
- package/dist/individuals/queue/queue.mjs +1865 -0
- package/dist/individuals/stack/stack.mjs +415 -0
- package/dist/individuals/trie/trie.mjs +687 -0
- package/dist/umd/data-structure-typed.js +14 -14
- package/dist/umd/data-structure-typed.min.js +2 -2
- package/dist/umd/data-structure-typed.min.js.map +1 -1
- package/package.json +2 -2
- package/src/data-structures/graph/abstract-graph.ts +14 -14
- package/src/data-structures/hash/hash-map.ts +46 -0
- package/src/data-structures/linked-list/singly-linked-list.ts +66 -0
- package/src/data-structures/queue/queue.ts +47 -0
- package/src/data-structures/stack/stack.ts +121 -0
- package/test/unit/data-structures/graph/directed-graph.test.ts +37 -37
- package/test/unit/data-structures/graph/undirected-graph.test.ts +2 -2
- package/test/unit/data-structures/hash/hash-map.test.ts +135 -0
- package/test/unit/data-structures/linked-list/singly-linked-list.test.ts +72 -1
- package/test/unit/data-structures/queue/queue.test.ts +214 -0
- package/test/unit/data-structures/stack/stack.test.ts +165 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "data-structure-typed",
|
|
3
|
-
"version": "2.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "2.0.1",
|
|
4
|
+
"description": "Standard data structure",
|
|
5
5
|
"main": "dist/cjs/index.js",
|
|
6
6
|
"module": "dist/esm/index.js",
|
|
7
7
|
"browser": "dist/umd/data-structure-typed.min.js",
|
|
@@ -339,7 +339,7 @@ export abstract class AbstractGraph<
|
|
|
339
339
|
|
|
340
340
|
if (isWeight) {
|
|
341
341
|
const allPaths = this.getAllPathsBetween(v1, v2);
|
|
342
|
-
let min =
|
|
342
|
+
let min = Number.MAX_SAFE_INTEGER;
|
|
343
343
|
for (const path of allPaths) {
|
|
344
344
|
min = Math.min(this.getPathSumWeight(path), min);
|
|
345
345
|
}
|
|
@@ -404,7 +404,7 @@ export abstract class AbstractGraph<
|
|
|
404
404
|
if (isWeight) {
|
|
405
405
|
if (isDFS) {
|
|
406
406
|
const allPaths = this.getAllPathsBetween(v1, v2, 10000);
|
|
407
|
-
let min =
|
|
407
|
+
let min = Number.MAX_SAFE_INTEGER;
|
|
408
408
|
let minIndex = -1;
|
|
409
409
|
let index = 0;
|
|
410
410
|
for (const path of allPaths) {
|
|
@@ -475,7 +475,7 @@ export abstract class AbstractGraph<
|
|
|
475
475
|
getMinDist: boolean = false,
|
|
476
476
|
genPaths: boolean = false
|
|
477
477
|
): DijkstraResult<VO> {
|
|
478
|
-
let minDist =
|
|
478
|
+
let minDist = Number.MAX_SAFE_INTEGER;
|
|
479
479
|
let minDest: VO | undefined = undefined;
|
|
480
480
|
let minPath: VO[] = [];
|
|
481
481
|
const paths: VO[][] = [];
|
|
@@ -494,13 +494,13 @@ export abstract class AbstractGraph<
|
|
|
494
494
|
|
|
495
495
|
for (const vertex of vertexMap) {
|
|
496
496
|
const vertexOrKey = vertex[1];
|
|
497
|
-
if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey,
|
|
497
|
+
if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);
|
|
498
498
|
}
|
|
499
499
|
distMap.set(srcVertex, 0);
|
|
500
500
|
preMap.set(srcVertex, undefined);
|
|
501
501
|
|
|
502
502
|
const getMinOfNoSeen = () => {
|
|
503
|
-
let min =
|
|
503
|
+
let min = Number.MAX_SAFE_INTEGER;
|
|
504
504
|
let minV: VO | undefined = undefined;
|
|
505
505
|
for (const [key, value] of distMap) {
|
|
506
506
|
if (!seen.has(key)) {
|
|
@@ -537,7 +537,7 @@ export abstract class AbstractGraph<
|
|
|
537
537
|
seen.add(cur);
|
|
538
538
|
if (destVertex && destVertex === cur) {
|
|
539
539
|
if (getMinDist) {
|
|
540
|
-
minDist = distMap.get(destVertex) ||
|
|
540
|
+
minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;
|
|
541
541
|
}
|
|
542
542
|
if (genPaths) {
|
|
543
543
|
getPaths(destVertex);
|
|
@@ -605,7 +605,7 @@ export abstract class AbstractGraph<
|
|
|
605
605
|
getMinDist: boolean = false,
|
|
606
606
|
genPaths: boolean = false
|
|
607
607
|
): DijkstraResult<VO> {
|
|
608
|
-
let minDist =
|
|
608
|
+
let minDist = Number.MAX_SAFE_INTEGER;
|
|
609
609
|
let minDest: VO | undefined = undefined;
|
|
610
610
|
let minPath: VO[] = [];
|
|
611
611
|
const paths: VO[][] = [];
|
|
@@ -621,7 +621,7 @@ export abstract class AbstractGraph<
|
|
|
621
621
|
|
|
622
622
|
for (const vertex of vertexMap) {
|
|
623
623
|
const vertexOrKey = vertex[1];
|
|
624
|
-
if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey,
|
|
624
|
+
if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);
|
|
625
625
|
}
|
|
626
626
|
|
|
627
627
|
const heap = new Heap<{ key: number; value: VO }>([], { comparator: (a, b) => a.key - b.key });
|
|
@@ -661,7 +661,7 @@ export abstract class AbstractGraph<
|
|
|
661
661
|
seen.add(cur);
|
|
662
662
|
if (destVertex && destVertex === cur) {
|
|
663
663
|
if (getMinDist) {
|
|
664
|
-
minDist = distMap.get(destVertex) ||
|
|
664
|
+
minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;
|
|
665
665
|
}
|
|
666
666
|
if (genPaths) {
|
|
667
667
|
getPaths(destVertex);
|
|
@@ -732,7 +732,7 @@ export abstract class AbstractGraph<
|
|
|
732
732
|
const paths: VO[][] = [];
|
|
733
733
|
const distMap: Map<VO, number> = new Map();
|
|
734
734
|
const preMap: Map<VO, VO> = new Map(); // predecessor
|
|
735
|
-
let min =
|
|
735
|
+
let min = Number.MAX_SAFE_INTEGER;
|
|
736
736
|
let minPath: VO[] = [];
|
|
737
737
|
// TODO
|
|
738
738
|
let hasNegativeCycle: boolean | undefined;
|
|
@@ -745,7 +745,7 @@ export abstract class AbstractGraph<
|
|
|
745
745
|
const numOfEdges = edgeMap.length;
|
|
746
746
|
|
|
747
747
|
this._vertexMap.forEach(vertex => {
|
|
748
|
-
distMap.set(vertex,
|
|
748
|
+
distMap.set(vertex, Number.MAX_SAFE_INTEGER);
|
|
749
749
|
});
|
|
750
750
|
|
|
751
751
|
distMap.set(srcVertex, 0);
|
|
@@ -759,7 +759,7 @@ export abstract class AbstractGraph<
|
|
|
759
759
|
const sWeight = distMap.get(s);
|
|
760
760
|
const dWeight = distMap.get(d);
|
|
761
761
|
if (sWeight !== undefined && dWeight !== undefined) {
|
|
762
|
-
if (distMap.get(s) !==
|
|
762
|
+
if (distMap.get(s) !== Number.MAX_SAFE_INTEGER && sWeight + weight < dWeight) {
|
|
763
763
|
distMap.set(d, sWeight + weight);
|
|
764
764
|
if (genPath) preMap.set(d, s);
|
|
765
765
|
}
|
|
@@ -804,7 +804,7 @@ export abstract class AbstractGraph<
|
|
|
804
804
|
const weight = edgeMap[j].weight;
|
|
805
805
|
const sWeight = distMap.get(s);
|
|
806
806
|
if (sWeight) {
|
|
807
|
-
if (sWeight !==
|
|
807
|
+
if (sWeight !== Number.MAX_SAFE_INTEGER && sWeight + weight < sWeight) hasNegativeCycle = true;
|
|
808
808
|
}
|
|
809
809
|
}
|
|
810
810
|
}
|
|
@@ -860,7 +860,7 @@ export abstract class AbstractGraph<
|
|
|
860
860
|
|
|
861
861
|
for (let i = 0; i < n; i++) {
|
|
862
862
|
for (let j = 0; j < n; j++) {
|
|
863
|
-
costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight ||
|
|
863
|
+
costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight || Number.MAX_SAFE_INTEGER;
|
|
864
864
|
}
|
|
865
865
|
}
|
|
866
866
|
|
|
@@ -21,6 +21,52 @@ import { isWeakKey, rangeCheck } from '../../utils';
|
|
|
21
21
|
* 3. Unique Keys: Keys are unique.
|
|
22
22
|
* If you try to insert another entry with the same key, the new one will replace the old entry.
|
|
23
23
|
* 4. Unordered Collection: HashMap does not guarantee the order of entries, and the order may change over time.
|
|
24
|
+
* @example
|
|
25
|
+
* // should maintain insertion order
|
|
26
|
+
* const linkedHashMap = new LinkedHashMap<number, string>();
|
|
27
|
+
* linkedHashMap.set(1, 'A');
|
|
28
|
+
* linkedHashMap.set(2, 'B');
|
|
29
|
+
* linkedHashMap.set(3, 'C');
|
|
30
|
+
*
|
|
31
|
+
* const result = Array.from(linkedHashMap);
|
|
32
|
+
* console.log(result); // [
|
|
33
|
+
* // [1, 'A'],
|
|
34
|
+
* // [2, 'B'],
|
|
35
|
+
* // [3, 'C']
|
|
36
|
+
* // ]
|
|
37
|
+
* @example
|
|
38
|
+
* // fast lookup of values by key
|
|
39
|
+
* const hashMap = new HashMap<number, string>();
|
|
40
|
+
* hashMap.set(1, 'A');
|
|
41
|
+
* hashMap.set(2, 'B');
|
|
42
|
+
* hashMap.set(3, 'C');
|
|
43
|
+
*
|
|
44
|
+
* console.log(hashMap.get(1)); // 'A'
|
|
45
|
+
* console.log(hashMap.get(2)); // 'B'
|
|
46
|
+
* console.log(hashMap.get(3)); // 'C'
|
|
47
|
+
* console.log(hashMap.get(99)); // undefined
|
|
48
|
+
* @example
|
|
49
|
+
* // remove duplicates when adding multiple entries
|
|
50
|
+
* const hashMap = new HashMap<number, string>();
|
|
51
|
+
* hashMap.set(1, 'A');
|
|
52
|
+
* hashMap.set(2, 'B');
|
|
53
|
+
* hashMap.set(1, 'C'); // Update value for key 1
|
|
54
|
+
*
|
|
55
|
+
* console.log(hashMap.size); // 2
|
|
56
|
+
* console.log(hashMap.get(1)); // 'C'
|
|
57
|
+
* console.log(hashMap.get(2)); // 'B'
|
|
58
|
+
* @example
|
|
59
|
+
* // count occurrences of keys
|
|
60
|
+
* const data = [1, 2, 1, 3, 2, 1];
|
|
61
|
+
*
|
|
62
|
+
* const countMap = new HashMap<number, number>();
|
|
63
|
+
* for (const key of data) {
|
|
64
|
+
* countMap.set(key, (countMap.get(key) || 0) + 1);
|
|
65
|
+
* }
|
|
66
|
+
*
|
|
67
|
+
* console.log(countMap.get(1)); // 3
|
|
68
|
+
* console.log(countMap.get(2)); // 2
|
|
69
|
+
* console.log(countMap.get(3)); // 1
|
|
24
70
|
*/
|
|
25
71
|
export class HashMap<K = any, V = any, R = [K, V]> extends IterableEntryBase<K, V> {
|
|
26
72
|
/**
|
|
@@ -38,6 +38,72 @@ export class SinglyLinkedListNode<E = any> extends LinkedListNode<E> {
|
|
|
38
38
|
* 4. High Efficiency in Insertion and Deletion: Adding or removing elements in a linked list does not require moving other elements, making these operations more efficient than in arrays.
|
|
39
39
|
* Caution: Although our linked list classes provide methods such as at, setAt, addAt, and indexOf that are based on array indices, their time complexity, like that of the native Array.lastIndexOf, is 𝑂(𝑛). If you need to use these methods frequently, you might want to consider other data structures, such as Deque or Queue (designed for random access). Similarly, since the native Array.shift method has a time complexity of 𝑂(𝑛), using an array to simulate a queue can be inefficient. In such cases, you should use Queue or Deque, as these data structures leverage deferred array rearrangement, effectively reducing the average time complexity to 𝑂(1).
|
|
40
40
|
*
|
|
41
|
+
* @example
|
|
42
|
+
* // implementation of a basic text editor
|
|
43
|
+
* class TextEditor {
|
|
44
|
+
* private content: SinglyLinkedList<string>;
|
|
45
|
+
* private cursorIndex: number;
|
|
46
|
+
* private undoStack: Stack<{ operation: string; data?: any }>;
|
|
47
|
+
*
|
|
48
|
+
* constructor() {
|
|
49
|
+
* this.content = new SinglyLinkedList<string>();
|
|
50
|
+
* this.cursorIndex = 0; // Cursor starts at the beginning
|
|
51
|
+
* this.undoStack = new Stack<{ operation: string; data?: any }>(); // Stack to keep track of operations for undo
|
|
52
|
+
* }
|
|
53
|
+
*
|
|
54
|
+
* insert(char: string) {
|
|
55
|
+
* this.content.addAt(this.cursorIndex, char);
|
|
56
|
+
* this.cursorIndex++;
|
|
57
|
+
* this.undoStack.push({ operation: 'insert', data: { index: this.cursorIndex - 1 } });
|
|
58
|
+
* }
|
|
59
|
+
*
|
|
60
|
+
* delete() {
|
|
61
|
+
* if (this.cursorIndex === 0) return; // Nothing to delete
|
|
62
|
+
* const deleted = this.content.deleteAt(this.cursorIndex - 1);
|
|
63
|
+
* this.cursorIndex--;
|
|
64
|
+
* this.undoStack.push({ operation: 'delete', data: { index: this.cursorIndex, char: deleted } });
|
|
65
|
+
* }
|
|
66
|
+
*
|
|
67
|
+
* moveCursor(index: number) {
|
|
68
|
+
* this.cursorIndex = Math.max(0, Math.min(index, this.content.length));
|
|
69
|
+
* }
|
|
70
|
+
*
|
|
71
|
+
* undo() {
|
|
72
|
+
* if (this.undoStack.size === 0) return; // No operations to undo
|
|
73
|
+
* const lastAction = this.undoStack.pop();
|
|
74
|
+
*
|
|
75
|
+
* if (lastAction!.operation === 'insert') {
|
|
76
|
+
* this.content.deleteAt(lastAction!.data.index);
|
|
77
|
+
* this.cursorIndex = lastAction!.data.index;
|
|
78
|
+
* } else if (lastAction!.operation === 'delete') {
|
|
79
|
+
* this.content.addAt(lastAction!.data.index, lastAction!.data.char);
|
|
80
|
+
* this.cursorIndex = lastAction!.data.index + 1;
|
|
81
|
+
* }
|
|
82
|
+
* }
|
|
83
|
+
*
|
|
84
|
+
* getText(): string {
|
|
85
|
+
* return [...this.content].join('');
|
|
86
|
+
* }
|
|
87
|
+
* }
|
|
88
|
+
*
|
|
89
|
+
* // Example Usage
|
|
90
|
+
* const editor = new TextEditor();
|
|
91
|
+
* editor.insert('H');
|
|
92
|
+
* editor.insert('e');
|
|
93
|
+
* editor.insert('l');
|
|
94
|
+
* editor.insert('l');
|
|
95
|
+
* editor.insert('o');
|
|
96
|
+
* console.log(editor.getText()); // 'Hello' // Output: "Hello"
|
|
97
|
+
*
|
|
98
|
+
* editor.delete();
|
|
99
|
+
* console.log(editor.getText()); // 'Hell' // Output: "Hell"
|
|
100
|
+
*
|
|
101
|
+
* editor.undo();
|
|
102
|
+
* console.log(editor.getText()); // 'Hello' // Output: "Hello"
|
|
103
|
+
*
|
|
104
|
+
* editor.moveCursor(1);
|
|
105
|
+
* editor.insert('a');
|
|
106
|
+
* console.log(editor.getText()); // 'Haello'
|
|
41
107
|
*/
|
|
42
108
|
export class SinglyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, SinglyLinkedListNode<E>> {
|
|
43
109
|
constructor(
|
|
@@ -15,6 +15,53 @@ import { LinearBase } from '../base/linear-base';
|
|
|
15
15
|
* 5. Data Buffering: Acting as a buffer for data packets in network communication.
|
|
16
16
|
* 6. Breadth-First Search (BFS): In traversal algorithms for graphs and trees, queues store elements that are to be visited.
|
|
17
17
|
* 7. Real-time Queuing: Like queuing systems in banks or supermarkets.
|
|
18
|
+
* @example
|
|
19
|
+
* // Sliding Window using Queue
|
|
20
|
+
* const nums = [2, 3, 4, 1, 5];
|
|
21
|
+
* const k = 2;
|
|
22
|
+
* const queue = new Queue<number>();
|
|
23
|
+
*
|
|
24
|
+
* let maxSum = 0;
|
|
25
|
+
* let currentSum = 0;
|
|
26
|
+
*
|
|
27
|
+
* nums.forEach((num, i) => {
|
|
28
|
+
* queue.push(num);
|
|
29
|
+
* currentSum += num;
|
|
30
|
+
*
|
|
31
|
+
* if (queue.length > k) {
|
|
32
|
+
* currentSum -= queue.shift()!;
|
|
33
|
+
* }
|
|
34
|
+
*
|
|
35
|
+
* if (queue.length === k) {
|
|
36
|
+
* maxSum = Math.max(maxSum, currentSum);
|
|
37
|
+
* }
|
|
38
|
+
* });
|
|
39
|
+
*
|
|
40
|
+
* console.log(maxSum); // 7
|
|
41
|
+
* @example
|
|
42
|
+
* // Breadth-First Search (BFS) using Queue
|
|
43
|
+
* const graph: { [key in number]: number[] } = {
|
|
44
|
+
* 1: [2, 3],
|
|
45
|
+
* 2: [4, 5],
|
|
46
|
+
* 3: [],
|
|
47
|
+
* 4: [],
|
|
48
|
+
* 5: []
|
|
49
|
+
* };
|
|
50
|
+
*
|
|
51
|
+
* const queue = new Queue<number>();
|
|
52
|
+
* const visited: number[] = [];
|
|
53
|
+
*
|
|
54
|
+
* queue.push(1);
|
|
55
|
+
*
|
|
56
|
+
* while (!queue.isEmpty()) {
|
|
57
|
+
* const node = queue.shift()!;
|
|
58
|
+
* if (!visited.includes(node)) {
|
|
59
|
+
* visited.push(node);
|
|
60
|
+
* graph[node].forEach(neighbor => queue.push(neighbor));
|
|
61
|
+
* }
|
|
62
|
+
* }
|
|
63
|
+
*
|
|
64
|
+
* console.log(visited); // [1, 2, 3, 4, 5]
|
|
18
65
|
*/
|
|
19
66
|
export class Queue<E = any, R = any> extends LinearBase<E, R> {
|
|
20
67
|
constructor(elements: Iterable<E> | Iterable<R> = [], options?: QueueOptions<E, R>) {
|
|
@@ -15,6 +15,127 @@ import { IterableElementBase } from '../base';
|
|
|
15
15
|
* 4. Function Calls: In most modern programming languages, the records of function calls are managed through a stack. When a function is called, its record (including parameters, local variables, and return address) is 'pushed' into the stack. When the function returns, its record is 'popped' from the stack.
|
|
16
16
|
* 5. Expression Evaluation: Used for the evaluation of arithmetic or logical expressions, especially when dealing with parenthesis matching and operator precedence.
|
|
17
17
|
* 6. Backtracking Algorithms: In problems where multiple branches need to be explored but only one branch can be explored at a time, stacks can be used to save the state at each branching point.
|
|
18
|
+
* @example
|
|
19
|
+
* // Balanced Parentheses or Brackets
|
|
20
|
+
* type ValidCharacters = ')' | '(' | ']' | '[' | '}' | '{';
|
|
21
|
+
*
|
|
22
|
+
* const stack = new Stack<string>();
|
|
23
|
+
* const input: ValidCharacters[] = '[({})]'.split('') as ValidCharacters[];
|
|
24
|
+
* const matches: { [key in ValidCharacters]?: ValidCharacters } = { ')': '(', ']': '[', '}': '{' };
|
|
25
|
+
* for (const char of input) {
|
|
26
|
+
* if ('([{'.includes(char)) {
|
|
27
|
+
* stack.push(char);
|
|
28
|
+
* } else if (')]}'.includes(char)) {
|
|
29
|
+
* if (stack.pop() !== matches[char]) {
|
|
30
|
+
* fail('Parentheses are not balanced');
|
|
31
|
+
* }
|
|
32
|
+
* }
|
|
33
|
+
* }
|
|
34
|
+
* console.log(stack.isEmpty()); // true
|
|
35
|
+
* @example
|
|
36
|
+
* // Expression Evaluation and Conversion
|
|
37
|
+
* const stack = new Stack<number>();
|
|
38
|
+
* const expression = [5, 3, '+']; // Equivalent to 5 + 3
|
|
39
|
+
* expression.forEach(token => {
|
|
40
|
+
* if (typeof token === 'number') {
|
|
41
|
+
* stack.push(token);
|
|
42
|
+
* } else {
|
|
43
|
+
* const b = stack.pop()!;
|
|
44
|
+
* const a = stack.pop()!;
|
|
45
|
+
* stack.push(token === '+' ? a + b : 0); // Only handling '+' here
|
|
46
|
+
* }
|
|
47
|
+
* });
|
|
48
|
+
* console.log(stack.pop()); // 8
|
|
49
|
+
* @example
|
|
50
|
+
* // Depth-First Search (DFS)
|
|
51
|
+
* const stack = new Stack<number>();
|
|
52
|
+
* const graph: { [key in number]: number[] } = { 1: [2, 3], 2: [4], 3: [5], 4: [], 5: [] };
|
|
53
|
+
* const visited: number[] = [];
|
|
54
|
+
* stack.push(1);
|
|
55
|
+
* while (!stack.isEmpty()) {
|
|
56
|
+
* const node = stack.pop()!;
|
|
57
|
+
* if (!visited.includes(node)) {
|
|
58
|
+
* visited.push(node);
|
|
59
|
+
* graph[node].forEach(neighbor => stack.push(neighbor));
|
|
60
|
+
* }
|
|
61
|
+
* }
|
|
62
|
+
* console.log(visited); // [1, 3, 5, 2, 4]
|
|
63
|
+
* @example
|
|
64
|
+
* // Backtracking Algorithms
|
|
65
|
+
* const stack = new Stack<[number, number]>();
|
|
66
|
+
* const maze = [
|
|
67
|
+
* ['S', ' ', 'X'],
|
|
68
|
+
* ['X', ' ', 'X'],
|
|
69
|
+
* [' ', ' ', 'E']
|
|
70
|
+
* ];
|
|
71
|
+
* const start: [number, number] = [0, 0];
|
|
72
|
+
* const end = [2, 2];
|
|
73
|
+
* const directions = [
|
|
74
|
+
* [0, 1], // To the right
|
|
75
|
+
* [1, 0], // down
|
|
76
|
+
* [0, -1], // left
|
|
77
|
+
* [-1, 0] // up
|
|
78
|
+
* ];
|
|
79
|
+
*
|
|
80
|
+
* const visited = new Set<string>(); // Used to record visited nodes
|
|
81
|
+
* stack.push(start);
|
|
82
|
+
* const path: number[][] = [];
|
|
83
|
+
*
|
|
84
|
+
* while (!stack.isEmpty()) {
|
|
85
|
+
* const [x, y] = stack.pop()!;
|
|
86
|
+
* if (visited.has(`${x},${y}`)) continue; // Skip already visited nodes
|
|
87
|
+
* visited.add(`${x},${y}`);
|
|
88
|
+
*
|
|
89
|
+
* path.push([x, y]);
|
|
90
|
+
*
|
|
91
|
+
* if (x === end[0] && y === end[1]) {
|
|
92
|
+
* break; // Find the end point and exit
|
|
93
|
+
* }
|
|
94
|
+
*
|
|
95
|
+
* for (const [dx, dy] of directions) {
|
|
96
|
+
* const nx = x + dx;
|
|
97
|
+
* const ny = y + dy;
|
|
98
|
+
* if (
|
|
99
|
+
* maze[nx]?.[ny] === ' ' || // feasible path
|
|
100
|
+
* maze[nx]?.[ny] === 'E' // destination
|
|
101
|
+
* ) {
|
|
102
|
+
* stack.push([nx, ny]);
|
|
103
|
+
* }
|
|
104
|
+
* }
|
|
105
|
+
* }
|
|
106
|
+
*
|
|
107
|
+
* expect(path).toContainEqual(end);
|
|
108
|
+
* @example
|
|
109
|
+
* // Function Call Stack
|
|
110
|
+
* const functionStack = new Stack<string>();
|
|
111
|
+
* functionStack.push('main');
|
|
112
|
+
* functionStack.push('foo');
|
|
113
|
+
* functionStack.push('bar');
|
|
114
|
+
* console.log(functionStack.pop()); // 'bar'
|
|
115
|
+
* console.log(functionStack.pop()); // 'foo'
|
|
116
|
+
* console.log(functionStack.pop()); // 'main'
|
|
117
|
+
* @example
|
|
118
|
+
* // Simplify File Paths
|
|
119
|
+
* const stack = new Stack<string>();
|
|
120
|
+
* const path = '/a/./b/../../c';
|
|
121
|
+
* path.split('/').forEach(segment => {
|
|
122
|
+
* if (segment === '..') stack.pop();
|
|
123
|
+
* else if (segment && segment !== '.') stack.push(segment);
|
|
124
|
+
* });
|
|
125
|
+
* console.log(stack.elements.join('/')); // 'c'
|
|
126
|
+
* @example
|
|
127
|
+
* // Stock Span Problem
|
|
128
|
+
* const stack = new Stack<number>();
|
|
129
|
+
* const prices = [100, 80, 60, 70, 60, 75, 85];
|
|
130
|
+
* const spans: number[] = [];
|
|
131
|
+
* prices.forEach((price, i) => {
|
|
132
|
+
* while (!stack.isEmpty() && prices[stack.peek()!] <= price) {
|
|
133
|
+
* stack.pop();
|
|
134
|
+
* }
|
|
135
|
+
* spans.push(stack.isEmpty() ? i + 1 : i - stack.peek()!);
|
|
136
|
+
* stack.push(i);
|
|
137
|
+
* });
|
|
138
|
+
* console.log(spans); // [1, 1, 1, 2, 1, 4, 6]
|
|
18
139
|
*/
|
|
19
140
|
export class Stack<E = any, R = any> extends IterableElementBase<E, R> {
|
|
20
141
|
constructor(elements: Iterable<E> | Iterable<R> = [], options?: StackOptions<E, R>) {
|
|
@@ -341,9 +341,9 @@ describe('Inherit from DirectedGraph and perform operations test2.', () => {
|
|
|
341
341
|
expect(distMap.get(vertex3)).toBe(35);
|
|
342
342
|
expect(distMap.get(vertex4)).toBe(14);
|
|
343
343
|
expect(distMap.get(vertex5)).toBe(70);
|
|
344
|
-
expect(distMap.get(vertex6)).toBe(
|
|
344
|
+
expect(distMap.get(vertex6)).toBe(Number.MAX_SAFE_INTEGER);
|
|
345
345
|
expect(distMap.get(vertex7)).toBe(61);
|
|
346
|
-
expect(distMap.get(vertex8)).toBe(
|
|
346
|
+
expect(distMap.get(vertex8)).toBe(Number.MAX_SAFE_INTEGER);
|
|
347
347
|
expect(distMap.get(vertex9)).toBe(19);
|
|
348
348
|
|
|
349
349
|
expect(preMap).toBeInstanceOf(Map);
|
|
@@ -351,7 +351,7 @@ describe('Inherit from DirectedGraph and perform operations test2.', () => {
|
|
|
351
351
|
|
|
352
352
|
expect(paths).toBeInstanceOf(Array);
|
|
353
353
|
expect(paths.length).toBe(0);
|
|
354
|
-
expect(min).toBe(
|
|
354
|
+
expect(min).toBe(Number.MAX_SAFE_INTEGER);
|
|
355
355
|
expect(minPath).toBeInstanceOf(Array);
|
|
356
356
|
|
|
357
357
|
const floydResult = myGraph.floydWarshall();
|
|
@@ -360,35 +360,35 @@ describe('Inherit from DirectedGraph and perform operations test2.', () => {
|
|
|
360
360
|
const { costs, predecessor } = floydResult;
|
|
361
361
|
expect(costs).toBeInstanceOf(Array);
|
|
362
362
|
expect(costs.length).toBe(9);
|
|
363
|
-
expect(costs[0]).toEqual([32, 12, 35, 14, 70,
|
|
364
|
-
expect(costs[1]).toEqual([20, 32, 23, 34, 58,
|
|
365
|
-
expect(costs[2]).toEqual([3, 15, 38, 17, 35,
|
|
366
|
-
expect(costs[3]).toEqual([123, 135, 120, 137, 155,
|
|
367
|
-
expect(costs[4]).toEqual([133, 145, 130, 147, 165,
|
|
363
|
+
expect(costs[0]).toEqual([32, 12, 35, 14, 70, Number.MAX_SAFE_INTEGER, 61, Number.MAX_SAFE_INTEGER, 19]);
|
|
364
|
+
expect(costs[1]).toEqual([20, 32, 23, 34, 58, Number.MAX_SAFE_INTEGER, 81, Number.MAX_SAFE_INTEGER, 39]);
|
|
365
|
+
expect(costs[2]).toEqual([3, 15, 38, 17, 35, Number.MAX_SAFE_INTEGER, 64, Number.MAX_SAFE_INTEGER, 22]);
|
|
366
|
+
expect(costs[3]).toEqual([123, 135, 120, 137, 155, Number.MAX_SAFE_INTEGER, 47, Number.MAX_SAFE_INTEGER, 126]);
|
|
367
|
+
expect(costs[4]).toEqual([133, 145, 130, 147, 165, Number.MAX_SAFE_INTEGER, 57, Number.MAX_SAFE_INTEGER, 136]);
|
|
368
368
|
expect(costs[5]).toEqual([
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
369
|
+
Number.MAX_SAFE_INTEGER,
|
|
370
|
+
Number.MAX_SAFE_INTEGER,
|
|
371
|
+
Number.MAX_SAFE_INTEGER,
|
|
372
|
+
Number.MAX_SAFE_INTEGER,
|
|
373
|
+
Number.MAX_SAFE_INTEGER,
|
|
374
|
+
Number.MAX_SAFE_INTEGER,
|
|
375
|
+
Number.MAX_SAFE_INTEGER,
|
|
376
|
+
Number.MAX_SAFE_INTEGER,
|
|
377
|
+
Number.MAX_SAFE_INTEGER
|
|
378
378
|
]);
|
|
379
|
-
expect(costs[6]).toEqual([76, 88, 73, 90, 108,
|
|
379
|
+
expect(costs[6]).toEqual([76, 88, 73, 90, 108, Number.MAX_SAFE_INTEGER, 137, Number.MAX_SAFE_INTEGER, 79]);
|
|
380
380
|
expect(costs[7]).toEqual([
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
381
|
+
Number.MAX_SAFE_INTEGER,
|
|
382
|
+
Number.MAX_SAFE_INTEGER,
|
|
383
|
+
Number.MAX_SAFE_INTEGER,
|
|
384
|
+
Number.MAX_SAFE_INTEGER,
|
|
385
|
+
Number.MAX_SAFE_INTEGER,
|
|
386
|
+
Number.MAX_SAFE_INTEGER,
|
|
387
|
+
Number.MAX_SAFE_INTEGER,
|
|
388
|
+
Number.MAX_SAFE_INTEGER,
|
|
389
|
+
Number.MAX_SAFE_INTEGER
|
|
390
390
|
]);
|
|
391
|
-
expect(costs[8]).toEqual([173, 185, 170, 187, 205,
|
|
391
|
+
expect(costs[8]).toEqual([173, 185, 170, 187, 205, Number.MAX_SAFE_INTEGER, 97, Number.MAX_SAFE_INTEGER, 176]);
|
|
392
392
|
|
|
393
393
|
expect(predecessor).toBeInstanceOf(Array);
|
|
394
394
|
expect(predecessor.length).toBe(9);
|
|
@@ -458,12 +458,12 @@ describe('Inherit from DirectedGraph and perform operations test2.', () => {
|
|
|
458
458
|
expect(distMap.size).toBe(9);
|
|
459
459
|
expect(distMap.get(vertex1)).toBe(0);
|
|
460
460
|
expect(distMap.get(vertex2)).toBe(12);
|
|
461
|
-
expect(distMap.get(vertex3)).toBe(
|
|
461
|
+
expect(distMap.get(vertex3)).toBe(Number.MAX_SAFE_INTEGER);
|
|
462
462
|
expect(distMap.get(vertex4)).toBe(14);
|
|
463
|
-
expect(distMap.get(vertex5)).toBe(
|
|
464
|
-
expect(distMap.get(vertex6)).toBe(
|
|
465
|
-
expect(distMap.get(vertex7)).toBe(
|
|
466
|
-
expect(distMap.get(vertex8)).toBe(
|
|
463
|
+
expect(distMap.get(vertex5)).toBe(Number.MAX_SAFE_INTEGER);
|
|
464
|
+
expect(distMap.get(vertex6)).toBe(Number.MAX_SAFE_INTEGER);
|
|
465
|
+
expect(distMap.get(vertex7)).toBe(Number.MAX_SAFE_INTEGER);
|
|
466
|
+
expect(distMap.get(vertex8)).toBe(Number.MAX_SAFE_INTEGER);
|
|
467
467
|
expect(distMap.get(vertex9)).toBe(19);
|
|
468
468
|
|
|
469
469
|
expect(minDist).toBe(12);
|
|
@@ -512,9 +512,9 @@ describe('Inherit from DirectedGraph and perform operations test2.', () => {
|
|
|
512
512
|
expect(distMap.get(vertex3)).toBe(35);
|
|
513
513
|
expect(distMap.get(vertex4)).toBe(14);
|
|
514
514
|
expect(distMap.get(vertex5)).toBe(70);
|
|
515
|
-
expect(distMap.get(vertex6)).toBe(
|
|
515
|
+
expect(distMap.get(vertex6)).toBe(Number.MAX_SAFE_INTEGER);
|
|
516
516
|
expect(distMap.get(vertex7)).toBe(61);
|
|
517
|
-
expect(distMap.get(vertex8)).toBe(
|
|
517
|
+
expect(distMap.get(vertex8)).toBe(Number.MAX_SAFE_INTEGER);
|
|
518
518
|
expect(distMap.get(vertex9)).toBe(19);
|
|
519
519
|
|
|
520
520
|
expect(minDist).toBe(12);
|
|
@@ -574,9 +574,9 @@ describe('Inherit from DirectedGraph and perform operations test2.', () => {
|
|
|
574
574
|
expect(distMap.get(vertex3)).toBe(35);
|
|
575
575
|
expect(distMap.get(vertex4)).toBe(14);
|
|
576
576
|
expect(distMap.get(vertex5)).toBe(70);
|
|
577
|
-
expect(distMap.get(vertex6)).toBe(
|
|
577
|
+
expect(distMap.get(vertex6)).toBe(Number.MAX_SAFE_INTEGER);
|
|
578
578
|
expect(distMap.get(vertex7)).toBe(61);
|
|
579
|
-
expect(distMap.get(vertex8)).toBe(
|
|
579
|
+
expect(distMap.get(vertex8)).toBe(Number.MAX_SAFE_INTEGER);
|
|
580
580
|
expect(distMap.get(vertex9)).toBe(19);
|
|
581
581
|
|
|
582
582
|
expect(minDist).toBe(12);
|
|
@@ -264,7 +264,7 @@ describe('cycles, strongly connected components, bridges, articular points in Un
|
|
|
264
264
|
expect(lowMap.size).toBe(8);
|
|
265
265
|
});
|
|
266
266
|
|
|
267
|
-
it('Should return
|
|
267
|
+
it('Should return Number.MAX_SAFE_INTEGER if dest is not found', () => {
|
|
268
268
|
const graph = new UndirectedGraph<string>();
|
|
269
269
|
|
|
270
270
|
for (let i = 0; i < 3; ++i) {
|
|
@@ -274,7 +274,7 @@ it('Should return Infinity if dest is not found', () => {
|
|
|
274
274
|
graph.addEdge(0, 1, 1);
|
|
275
275
|
|
|
276
276
|
const minCost02 = graph.getMinCostBetween(0, 2, true);
|
|
277
|
-
expect(minCost02).toBe(
|
|
277
|
+
expect(minCost02).toBe(Number.MAX_SAFE_INTEGER);
|
|
278
278
|
|
|
279
279
|
const minCost01 = graph.getMinCostBetween(0, 1, true);
|
|
280
280
|
expect(minCost01).toBe(1);
|