data-structure-typed 1.49.4 → 1.49.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/README.md +15 -26
  3. package/README_zh-CN.md +1 -1
  4. package/benchmark/report.html +14 -23
  5. package/benchmark/report.json +163 -256
  6. package/dist/cjs/data-structures/base/iterable-base.d.ts +1 -1
  7. package/dist/cjs/data-structures/base/iterable-base.js.map +1 -1
  8. package/dist/cjs/data-structures/binary-tree/avl-tree.d.ts +53 -48
  9. package/dist/cjs/data-structures/binary-tree/avl-tree.js +55 -49
  10. package/dist/cjs/data-structures/binary-tree/avl-tree.js.map +1 -1
  11. package/dist/cjs/data-structures/binary-tree/binary-tree.d.ts +154 -143
  12. package/dist/cjs/data-structures/binary-tree/binary-tree.js +211 -198
  13. package/dist/cjs/data-structures/binary-tree/binary-tree.js.map +1 -1
  14. package/dist/cjs/data-structures/binary-tree/bst.d.ts +83 -71
  15. package/dist/cjs/data-structures/binary-tree/bst.js +113 -89
  16. package/dist/cjs/data-structures/binary-tree/bst.js.map +1 -1
  17. package/dist/cjs/data-structures/binary-tree/rb-tree.d.ts +37 -35
  18. package/dist/cjs/data-structures/binary-tree/rb-tree.js +62 -59
  19. package/dist/cjs/data-structures/binary-tree/rb-tree.js.map +1 -1
  20. package/dist/cjs/data-structures/binary-tree/tree-multimap.d.ts +46 -55
  21. package/dist/cjs/data-structures/binary-tree/tree-multimap.js +59 -94
  22. package/dist/cjs/data-structures/binary-tree/tree-multimap.js.map +1 -1
  23. package/dist/cjs/data-structures/graph/abstract-graph.d.ts +1 -1
  24. package/dist/cjs/data-structures/graph/abstract-graph.js +3 -2
  25. package/dist/cjs/data-structures/graph/abstract-graph.js.map +1 -1
  26. package/dist/cjs/data-structures/graph/directed-graph.js.map +1 -1
  27. package/dist/cjs/data-structures/graph/map-graph.js.map +1 -1
  28. package/dist/cjs/data-structures/graph/undirected-graph.js.map +1 -1
  29. package/dist/cjs/data-structures/hash/hash-map.d.ts +1 -1
  30. package/dist/cjs/data-structures/hash/hash-map.js +2 -2
  31. package/dist/cjs/data-structures/hash/hash-map.js.map +1 -1
  32. package/dist/cjs/data-structures/heap/heap.js +2 -3
  33. package/dist/cjs/data-structures/heap/heap.js.map +1 -1
  34. package/dist/cjs/data-structures/heap/max-heap.js.map +1 -1
  35. package/dist/cjs/data-structures/heap/min-heap.js.map +1 -1
  36. package/dist/cjs/data-structures/linked-list/singly-linked-list.d.ts +2 -2
  37. package/dist/cjs/data-structures/linked-list/singly-linked-list.js.map +1 -1
  38. package/dist/cjs/data-structures/matrix/index.d.ts +0 -2
  39. package/dist/cjs/data-structures/matrix/index.js +0 -2
  40. package/dist/cjs/data-structures/matrix/index.js.map +1 -1
  41. package/dist/cjs/data-structures/matrix/matrix.d.ts +128 -10
  42. package/dist/cjs/data-structures/matrix/matrix.js +400 -15
  43. package/dist/cjs/data-structures/matrix/matrix.js.map +1 -1
  44. package/dist/cjs/data-structures/priority-queue/min-priority-queue.js.map +1 -1
  45. package/dist/cjs/data-structures/queue/deque.d.ts +2 -2
  46. package/dist/cjs/data-structures/queue/deque.js +5 -7
  47. package/dist/cjs/data-structures/queue/deque.js.map +1 -1
  48. package/dist/cjs/data-structures/queue/queue.d.ts +1 -1
  49. package/dist/cjs/interfaces/binary-tree.d.ts +3 -3
  50. package/dist/cjs/types/common.d.ts +3 -3
  51. package/dist/cjs/types/common.js +2 -2
  52. package/dist/cjs/types/common.js.map +1 -1
  53. package/dist/cjs/types/data-structures/base/base.d.ts +1 -1
  54. package/dist/cjs/types/data-structures/heap/heap.d.ts +1 -1
  55. package/dist/cjs/types/data-structures/priority-queue/priority-queue.d.ts +1 -1
  56. package/dist/cjs/utils/utils.d.ts +1 -0
  57. package/dist/cjs/utils/utils.js +6 -1
  58. package/dist/cjs/utils/utils.js.map +1 -1
  59. package/dist/mjs/data-structures/base/iterable-base.d.ts +1 -1
  60. package/dist/mjs/data-structures/binary-tree/avl-tree.d.ts +53 -48
  61. package/dist/mjs/data-structures/binary-tree/avl-tree.js +57 -50
  62. package/dist/mjs/data-structures/binary-tree/binary-tree.d.ts +154 -143
  63. package/dist/mjs/data-structures/binary-tree/binary-tree.js +212 -199
  64. package/dist/mjs/data-structures/binary-tree/bst.d.ts +83 -71
  65. package/dist/mjs/data-structures/binary-tree/bst.js +115 -90
  66. package/dist/mjs/data-structures/binary-tree/rb-tree.d.ts +37 -35
  67. package/dist/mjs/data-structures/binary-tree/rb-tree.js +64 -60
  68. package/dist/mjs/data-structures/binary-tree/tree-multimap.d.ts +46 -55
  69. package/dist/mjs/data-structures/binary-tree/tree-multimap.js +61 -95
  70. package/dist/mjs/data-structures/graph/abstract-graph.d.ts +1 -1
  71. package/dist/mjs/data-structures/graph/abstract-graph.js +4 -3
  72. package/dist/mjs/data-structures/hash/hash-map.d.ts +1 -1
  73. package/dist/mjs/data-structures/hash/hash-map.js +2 -2
  74. package/dist/mjs/data-structures/heap/heap.js +2 -3
  75. package/dist/mjs/data-structures/linked-list/singly-linked-list.d.ts +2 -2
  76. package/dist/mjs/data-structures/linked-list/singly-linked-list.js +1 -1
  77. package/dist/mjs/data-structures/matrix/index.d.ts +0 -2
  78. package/dist/mjs/data-structures/matrix/index.js +0 -2
  79. package/dist/mjs/data-structures/matrix/matrix.d.ts +128 -10
  80. package/dist/mjs/data-structures/matrix/matrix.js +399 -16
  81. package/dist/mjs/data-structures/queue/deque.d.ts +2 -2
  82. package/dist/mjs/data-structures/queue/deque.js +7 -9
  83. package/dist/mjs/data-structures/queue/queue.d.ts +1 -1
  84. package/dist/mjs/data-structures/queue/queue.js +1 -1
  85. package/dist/mjs/interfaces/binary-tree.d.ts +3 -3
  86. package/dist/mjs/types/common.d.ts +3 -3
  87. package/dist/mjs/types/common.js +2 -2
  88. package/dist/mjs/types/data-structures/base/base.d.ts +1 -1
  89. package/dist/mjs/types/data-structures/heap/heap.d.ts +1 -1
  90. package/dist/mjs/types/data-structures/priority-queue/priority-queue.d.ts +1 -1
  91. package/dist/mjs/utils/utils.d.ts +1 -0
  92. package/dist/mjs/utils/utils.js +4 -0
  93. package/dist/umd/data-structure-typed.js +853 -943
  94. package/dist/umd/data-structure-typed.min.js +2 -2
  95. package/dist/umd/data-structure-typed.min.js.map +1 -1
  96. package/package.json +4 -3
  97. package/src/data-structures/base/index.ts +1 -1
  98. package/src/data-structures/base/iterable-base.ts +7 -10
  99. package/src/data-structures/binary-tree/avl-tree.ts +73 -61
  100. package/src/data-structures/binary-tree/binary-tree.ts +301 -270
  101. package/src/data-structures/binary-tree/bst.ts +139 -115
  102. package/src/data-structures/binary-tree/rb-tree.ts +81 -73
  103. package/src/data-structures/binary-tree/tree-multimap.ts +72 -103
  104. package/src/data-structures/graph/abstract-graph.ts +13 -11
  105. package/src/data-structures/graph/directed-graph.ts +1 -3
  106. package/src/data-structures/graph/map-graph.ts +6 -1
  107. package/src/data-structures/graph/undirected-graph.ts +3 -6
  108. package/src/data-structures/hash/hash-map.ts +18 -16
  109. package/src/data-structures/heap/heap.ts +7 -10
  110. package/src/data-structures/heap/max-heap.ts +2 -1
  111. package/src/data-structures/heap/min-heap.ts +2 -1
  112. package/src/data-structures/linked-list/singly-linked-list.ts +2 -3
  113. package/src/data-structures/matrix/index.ts +0 -2
  114. package/src/data-structures/matrix/matrix.ts +442 -13
  115. package/src/data-structures/priority-queue/min-priority-queue.ts +11 -10
  116. package/src/data-structures/queue/deque.ts +18 -39
  117. package/src/data-structures/queue/queue.ts +1 -1
  118. package/src/interfaces/binary-tree.ts +9 -4
  119. package/src/types/common.ts +5 -5
  120. package/src/types/data-structures/base/base.ts +14 -3
  121. package/src/types/data-structures/base/index.ts +1 -1
  122. package/src/types/data-structures/graph/abstract-graph.ts +4 -2
  123. package/src/types/data-structures/hash/hash-map.ts +3 -3
  124. package/src/types/data-structures/heap/heap.ts +2 -2
  125. package/src/types/data-structures/priority-queue/priority-queue.ts +2 -2
  126. package/src/utils/utils.ts +7 -1
  127. package/test/integration/avl-tree.test.ts +18 -1
  128. package/test/integration/bst.test.ts +2 -2
  129. package/test/performance/data-structures/binary-tree/avl-tree.test.ts +4 -12
  130. package/test/performance/data-structures/binary-tree/binary-tree-overall.test.ts +37 -0
  131. package/test/performance/data-structures/binary-tree/binary-tree.test.ts +6 -16
  132. package/test/performance/data-structures/binary-tree/bst.test.ts +5 -13
  133. package/test/performance/data-structures/binary-tree/rb-tree.test.ts +6 -16
  134. package/test/performance/data-structures/comparison/comparison.test.ts +19 -47
  135. package/test/performance/data-structures/graph/directed-graph.test.ts +3 -14
  136. package/test/performance/data-structures/hash/hash-map.test.ts +14 -38
  137. package/test/performance/data-structures/heap/heap.test.ts +5 -18
  138. package/test/performance/data-structures/linked-list/doubly-linked-list.test.ts +0 -2
  139. package/test/performance/data-structures/linked-list/singly-linked-list.test.ts +0 -2
  140. package/test/performance/data-structures/priority-queue/max-priority-queue.test.ts +2 -4
  141. package/test/performance/data-structures/priority-queue/priority-queue.test.ts +4 -14
  142. package/test/performance/data-structures/queue/deque.test.ts +6 -7
  143. package/test/performance/data-structures/queue/queue.test.ts +13 -29
  144. package/test/performance/data-structures/stack/stack.test.ts +6 -18
  145. package/test/performance/data-structures/trie/trie.test.ts +2 -6
  146. package/test/performance/reportor.ts +14 -15
  147. package/test/unit/data-structures/binary-tree/avl-tree.test.ts +14 -3
  148. package/test/unit/data-structures/binary-tree/binary-tree.test.ts +65 -29
  149. package/test/unit/data-structures/binary-tree/bst.test.ts +69 -27
  150. package/test/unit/data-structures/binary-tree/overall.test.ts +16 -18
  151. package/test/unit/data-structures/binary-tree/rb-tree.test.ts +17 -6
  152. package/test/unit/data-structures/binary-tree/tree-multimap.test.ts +37 -21
  153. package/test/unit/data-structures/graph/directed-graph.test.ts +104 -45
  154. package/test/unit/data-structures/graph/undirected-graph.test.ts +57 -40
  155. package/test/unit/data-structures/hash/hash-map.test.ts +48 -28
  156. package/test/unit/data-structures/hash/hash-table.test.ts +0 -4
  157. package/test/unit/data-structures/heap/heap.test.ts +0 -1
  158. package/test/unit/data-structures/heap/min-heap.test.ts +6 -5
  159. package/test/unit/data-structures/linked-list/doubly-linked-list.test.ts +10 -11
  160. package/test/unit/data-structures/linked-list/singly-linked-list.test.ts +3 -4
  161. package/test/unit/data-structures/matrix/matrix.test.ts +345 -52
  162. package/test/unit/data-structures/priority-queue/max-priority-queue.test.ts +1 -1
  163. package/test/unit/data-structures/priority-queue/priority-queue.test.ts +0 -1
  164. package/test/unit/data-structures/queue/deque.test.ts +0 -6
  165. package/test/unit/data-structures/queue/queue.test.ts +1 -1
  166. package/test/unit/data-structures/stack/stack.test.ts +3 -4
  167. package/test/unit/unrestricted-interconversion.test.ts +50 -44
  168. package/test/utils/performanc.ts +1 -1
  169. package/typedoc.json +30 -0
  170. package/dist/cjs/data-structures/matrix/matrix2d.d.ts +0 -107
  171. package/dist/cjs/data-structures/matrix/matrix2d.js +0 -200
  172. package/dist/cjs/data-structures/matrix/matrix2d.js.map +0 -1
  173. package/dist/cjs/data-structures/matrix/vector2d.d.ts +0 -200
  174. package/dist/cjs/data-structures/matrix/vector2d.js +0 -291
  175. package/dist/cjs/data-structures/matrix/vector2d.js.map +0 -1
  176. package/dist/mjs/data-structures/matrix/matrix2d.d.ts +0 -107
  177. package/dist/mjs/data-structures/matrix/matrix2d.js +0 -196
  178. package/dist/mjs/data-structures/matrix/vector2d.d.ts +0 -200
  179. package/dist/mjs/data-structures/matrix/vector2d.js +0 -289
  180. package/src/data-structures/matrix/matrix2d.ts +0 -211
  181. package/src/data-structures/matrix/vector2d.ts +0 -315
  182. package/test/performance/data-structures/binary-tree/overall.test.ts +0 -0
  183. package/test/performance/data-structures/matrix/matrix2d.test.ts +0 -0
  184. package/test/performance/data-structures/matrix/vector2d.test.ts +0 -0
  185. package/test/unit/data-structures/matrix/matrix2d.test.ts +0 -345
  186. package/test/unit/data-structures/matrix/vector2d.test.ts +0 -171
@@ -5,21 +5,404 @@
5
5
  * @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
6
6
  * @license MIT License
7
7
  */
8
- // todo need to be improved
9
- export class MatrixNTI2D {
10
- _matrix;
11
- /**
12
- * The constructor creates a matrix with the specified number of rows and columns, and initializes all elements to a
13
- * given initial value or 0 if not provided.
14
- * @param options - An object containing the following properties:
15
- */
16
- constructor(options) {
17
- const { row, col, initialVal } = options;
18
- this._matrix = new Array(row).fill(undefined).map(() => new Array(col).fill(initialVal || 0));
19
- }
20
- /* The `toArray` method returns the matrix as a two-dimensional array. It converts the internal representation of the
21
- matrix, which is an array of arrays, into a format that is more commonly used in JavaScript. */
22
- toArray() {
23
- return this._matrix;
8
+ export class Matrix {
9
+ /**
10
+ * The constructor function initializes a matrix object with the provided data and options, or with
11
+ * default values if no options are provided.
12
+ * @param {number[][]} data - A 2D array of numbers representing the data for the matrix.
13
+ * @param [options] - The `options` parameter is an optional object that can contain the following
14
+ * properties:
15
+ */
16
+ constructor(data, options) {
17
+ if (options) {
18
+ const { rows, cols, addFn, subtractFn, multiplyFn } = options;
19
+ if (typeof rows === 'number' && rows > 0)
20
+ this._rows = rows;
21
+ else
22
+ this._rows = data.length;
23
+ if (typeof cols === 'number' && cols > 0)
24
+ this._cols = cols;
25
+ else
26
+ this._cols = data[0]?.length || 0;
27
+ if (addFn)
28
+ this._addFn = addFn;
29
+ if (subtractFn)
30
+ this._subtractFn = subtractFn;
31
+ if (multiplyFn)
32
+ this._multiplyFn = multiplyFn;
33
+ }
34
+ else {
35
+ this._rows = data.length;
36
+ this._cols = data[0]?.length ?? 0;
37
+ }
38
+ if (data.length > 0) {
39
+ this._data = data;
40
+ }
41
+ else {
42
+ this._data = [];
43
+ for (let i = 0; i < this.rows; i++) {
44
+ this._data[i] = new Array(this.cols).fill(0);
45
+ }
46
+ }
47
+ }
48
+ _rows = 0;
49
+ get rows() {
50
+ return this._rows;
51
+ }
52
+ _cols = 0;
53
+ get cols() {
54
+ return this._cols;
55
+ }
56
+ _data;
57
+ get data() {
58
+ return this._data;
59
+ }
60
+ get addFn() {
61
+ return this._addFn;
62
+ }
63
+ get subtractFn() {
64
+ return this._subtractFn;
65
+ }
66
+ get multiplyFn() {
67
+ return this._multiplyFn;
68
+ }
69
+ /**
70
+ * The `get` function returns the value at the specified row and column index if it is a valid index.
71
+ * @param {number} row - The `row` parameter represents the row index of the element you want to
72
+ * retrieve from the data array.
73
+ * @param {number} col - The parameter "col" represents the column number of the element you want to
74
+ * retrieve from the data array.
75
+ * @returns The `get` function returns a number if the provided row and column indices are valid.
76
+ * Otherwise, it returns `undefined`.
77
+ */
78
+ get(row, col) {
79
+ if (this.isValidIndex(row, col)) {
80
+ return this.data[row][col];
81
+ }
82
+ }
83
+ /**
84
+ * The set function updates the value at a specified row and column in a two-dimensional array.
85
+ * @param {number} row - The "row" parameter represents the row index of the element in a
86
+ * two-dimensional array or matrix. It specifies the row where the value will be set.
87
+ * @param {number} col - The "col" parameter represents the column index of the element in a
88
+ * two-dimensional array.
89
+ * @param {number} value - The value parameter represents the number that you want to set at the
90
+ * specified row and column in the data array.
91
+ * @returns a boolean value. It returns true if the index (row, col) is valid and the value is
92
+ * successfully set in the data array. It returns false if the index is invalid and the value is not
93
+ * set.
94
+ */
95
+ set(row, col, value) {
96
+ if (this.isValidIndex(row, col)) {
97
+ this.data[row][col] = value;
98
+ return true;
99
+ }
100
+ return false;
101
+ }
102
+ /**
103
+ * The function checks if the dimensions of the given matrix match the dimensions of the current
104
+ * matrix.
105
+ * @param {Matrix} matrix - The parameter `matrix` is of type `Matrix`.
106
+ * @returns a boolean value.
107
+ */
108
+ isMatchForCalculate(matrix) {
109
+ return this.rows === matrix.rows && this.cols === matrix.cols;
110
+ }
111
+ /**
112
+ * The `add` function adds two matrices together, returning a new matrix with the result.
113
+ * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
114
+ * @returns The `add` method returns a new `Matrix` object that represents the result of adding the
115
+ * current matrix with the provided `matrix` parameter.
116
+ */
117
+ add(matrix) {
118
+ if (!this.isMatchForCalculate(matrix)) {
119
+ throw new Error('Matrix dimensions must match for addition.');
120
+ }
121
+ const resultData = [];
122
+ for (let i = 0; i < this.rows; i++) {
123
+ resultData[i] = [];
124
+ for (let j = 0; j < this.cols; j++) {
125
+ const a = this.get(i, j), b = matrix.get(i, j);
126
+ if (a !== undefined && b !== undefined) {
127
+ const added = this._addFn(a, b);
128
+ if (added) {
129
+ resultData[i][j] = added;
130
+ }
131
+ }
132
+ }
133
+ }
134
+ return new Matrix(resultData, {
135
+ rows: this.rows,
136
+ cols: this.cols,
137
+ addFn: this.addFn,
138
+ subtractFn: this.subtractFn,
139
+ multiplyFn: this.multiplyFn
140
+ });
141
+ }
142
+ /**
143
+ * The `subtract` function performs element-wise subtraction between two matrices and returns a new
144
+ * matrix with the result.
145
+ * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class. It
146
+ * represents the matrix that you want to subtract from the current matrix.
147
+ * @returns a new Matrix object with the result of the subtraction operation.
148
+ */
149
+ subtract(matrix) {
150
+ if (!this.isMatchForCalculate(matrix)) {
151
+ throw new Error('Matrix dimensions must match for subtraction.');
152
+ }
153
+ const resultData = [];
154
+ for (let i = 0; i < this.rows; i++) {
155
+ resultData[i] = [];
156
+ for (let j = 0; j < this.cols; j++) {
157
+ const a = this.get(i, j), b = matrix.get(i, j);
158
+ if (a !== undefined && b !== undefined) {
159
+ const subtracted = this._subtractFn(a, b);
160
+ if (subtracted) {
161
+ resultData[i][j] = subtracted;
162
+ }
163
+ }
164
+ }
165
+ }
166
+ return new Matrix(resultData, {
167
+ rows: this.rows,
168
+ cols: this.cols,
169
+ addFn: this.addFn,
170
+ subtractFn: this.subtractFn,
171
+ multiplyFn: this.multiplyFn
172
+ });
173
+ }
174
+ /**
175
+ * The `multiply` function performs matrix multiplication between two matrices and returns the result
176
+ * as a new matrix.
177
+ * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
178
+ * @returns a new Matrix object.
179
+ */
180
+ multiply(matrix) {
181
+ if (this.cols !== matrix.rows) {
182
+ throw new Error('Matrix dimensions must be compatible for multiplication (A.cols = B.rows).');
183
+ }
184
+ const resultData = [];
185
+ for (let i = 0; i < this.rows; i++) {
186
+ resultData[i] = [];
187
+ for (let j = 0; j < matrix.cols; j++) {
188
+ let sum;
189
+ for (let k = 0; k < this.cols; k++) {
190
+ const a = this.get(i, k), b = matrix.get(k, j);
191
+ if (a !== undefined && b !== undefined) {
192
+ const multiplied = this.multiplyFn(a, b);
193
+ if (multiplied !== undefined) {
194
+ sum = this.addFn(sum, multiplied);
195
+ }
196
+ }
197
+ }
198
+ if (sum !== undefined)
199
+ resultData[i][j] = sum;
200
+ }
201
+ }
202
+ return new Matrix(resultData, {
203
+ rows: this.rows,
204
+ cols: matrix.cols,
205
+ addFn: this.addFn,
206
+ subtractFn: this.subtractFn,
207
+ multiplyFn: this.multiplyFn
208
+ });
209
+ }
210
+ /**
211
+ * The transpose function takes a matrix and returns a new matrix that is the transpose of the
212
+ * original matrix.
213
+ * @returns The transpose() function returns a new Matrix object with the transposed data.
214
+ */
215
+ transpose() {
216
+ if (this.data.some(row => row.length !== this.rows)) {
217
+ throw new Error('Matrix must be rectangular for transposition.');
218
+ }
219
+ const resultData = [];
220
+ for (let j = 0; j < this.cols; j++) {
221
+ resultData[j] = [];
222
+ for (let i = 0; i < this.rows; i++) {
223
+ const trans = this.get(i, j);
224
+ if (trans !== undefined)
225
+ resultData[j][i] = trans;
226
+ }
227
+ }
228
+ return new Matrix(resultData, {
229
+ rows: this.cols,
230
+ cols: this.rows,
231
+ addFn: this.addFn,
232
+ subtractFn: this.subtractFn,
233
+ multiplyFn: this.multiplyFn
234
+ });
235
+ }
236
+ /**
237
+ * The `inverse` function calculates the inverse of a square matrix using Gaussian elimination.
238
+ * @returns a Matrix object, which represents the inverse of the original matrix.
239
+ */
240
+ inverse() {
241
+ // Check if the matrix is square
242
+ if (this.rows !== this.cols) {
243
+ throw new Error('Matrix must be square for inversion.');
244
+ }
245
+ // Create an augmented matrix [this | I]
246
+ const augmentedMatrixData = [];
247
+ for (let i = 0; i < this.rows; i++) {
248
+ augmentedMatrixData[i] = this.data[i].slice(); // Copy the original matrix
249
+ for (let j = 0; j < this.cols; j++) {
250
+ augmentedMatrixData[i][this.cols + j] = i === j ? 1 : 0; // Append the identity matrix
251
+ }
252
+ }
253
+ const augmentedMatrix = new Matrix(augmentedMatrixData, {
254
+ rows: this.rows,
255
+ cols: this.cols * 2,
256
+ addFn: this.addFn,
257
+ subtractFn: this.subtractFn,
258
+ multiplyFn: this.multiplyFn
259
+ });
260
+ // Apply Gaussian elimination to transform the left half into the identity matrix
261
+ for (let i = 0; i < this.rows; i++) {
262
+ // Find pivot
263
+ let pivotRow = i;
264
+ while (pivotRow < this.rows && augmentedMatrix.get(pivotRow, i) === 0) {
265
+ pivotRow++;
266
+ }
267
+ if (pivotRow === this.rows) {
268
+ // Matrix is singular, and its inverse does not exist
269
+ throw new Error('Matrix is singular, and its inverse does not exist.');
270
+ }
271
+ // Swap rows to make the pivot the current row
272
+ augmentedMatrix._swapRows(i, pivotRow);
273
+ // Scale the pivot row to make the pivot element 1
274
+ const pivotElement = augmentedMatrix.get(i, i) ?? 1;
275
+ if (pivotElement === 0) {
276
+ // Handle division by zero
277
+ throw new Error('Matrix is singular, and its inverse does not exist (division by zero).');
278
+ }
279
+ augmentedMatrix._scaleRow(i, 1 / pivotElement);
280
+ // Eliminate other rows to make elements in the current column zero
281
+ for (let j = 0; j < this.rows; j++) {
282
+ if (j !== i) {
283
+ let factor = augmentedMatrix.get(j, i);
284
+ if (factor === undefined)
285
+ factor = 0;
286
+ augmentedMatrix._addScaledRow(j, i, -factor);
287
+ }
288
+ }
289
+ }
290
+ // Extract the right half of the augmented matrix as the inverse
291
+ const inverseData = [];
292
+ for (let i = 0; i < this.rows; i++) {
293
+ inverseData[i] = augmentedMatrix.data[i].slice(this.cols);
294
+ }
295
+ return new Matrix(inverseData, {
296
+ rows: this.rows,
297
+ cols: this.cols,
298
+ addFn: this.addFn,
299
+ subtractFn: this.subtractFn,
300
+ multiplyFn: this.multiplyFn
301
+ });
302
+ }
303
+ /**
304
+ * The dot function calculates the dot product of two matrices and returns a new matrix.
305
+ * @param {Matrix} matrix - The `matrix` parameter is an instance of the `Matrix` class.
306
+ * @returns a new Matrix object.
307
+ */
308
+ dot(matrix) {
309
+ if (this.cols !== matrix.rows) {
310
+ throw new Error('Number of columns in the first matrix must be equal to the number of rows in the second matrix for dot product.');
311
+ }
312
+ const resultData = [];
313
+ for (let i = 0; i < this.rows; i++) {
314
+ resultData[i] = [];
315
+ for (let j = 0; j < matrix.cols; j++) {
316
+ let sum;
317
+ for (let k = 0; k < this.cols; k++) {
318
+ const a = this.get(i, k), b = matrix.get(k, j);
319
+ if (a !== undefined && b !== undefined) {
320
+ const multiplied = this.multiplyFn(a, b);
321
+ if (multiplied !== undefined) {
322
+ sum = this.addFn(sum, multiplied);
323
+ }
324
+ }
325
+ }
326
+ if (sum !== undefined)
327
+ resultData[i][j] = sum;
328
+ }
329
+ }
330
+ return new Matrix(resultData, {
331
+ rows: this.rows,
332
+ cols: matrix.cols,
333
+ addFn: this.addFn,
334
+ subtractFn: this.subtractFn,
335
+ multiplyFn: this.multiplyFn
336
+ });
337
+ }
338
+ _addFn(a, b) {
339
+ if (a === undefined)
340
+ return b;
341
+ return a + b;
342
+ }
343
+ _subtractFn(a, b) {
344
+ return a - b;
345
+ }
346
+ _multiplyFn(a, b) {
347
+ return a * b;
348
+ }
349
+ /**
350
+ * The function checks if a given row and column index is valid within a specified range.
351
+ * @param {number} row - The `row` parameter represents the row index of a two-dimensional array or
352
+ * matrix. It is a number that indicates the specific row in the matrix.
353
+ * @param {number} col - The "col" parameter represents the column index in a two-dimensional array
354
+ * or grid. It is used to check if the given column index is valid within the bounds of the grid.
355
+ * @returns A boolean value is being returned.
356
+ */
357
+ isValidIndex(row, col) {
358
+ return row >= 0 && row < this.rows && col >= 0 && col < this.cols;
359
+ }
360
+ /**
361
+ * The function `_swapRows` swaps the positions of two rows in an array.
362
+ * @param {number} row1 - The `row1` parameter is the index of the first row that you want to swap.
363
+ * @param {number} row2 - The `row2` parameter is the index of the second row that you want to swap
364
+ * with the first row.
365
+ */
366
+ _swapRows(row1, row2) {
367
+ const temp = this.data[row1];
368
+ this.data[row1] = this.data[row2];
369
+ this.data[row2] = temp;
370
+ }
371
+ /**
372
+ * The function scales a specific row in a matrix by a given scalar value.
373
+ * @param {number} row - The `row` parameter represents the index of the row in the matrix that you
374
+ * want to scale. It is a number that indicates the position of the row within the matrix.
375
+ * @param {number} scalar - The scalar parameter is a number that is used to multiply each element in
376
+ * a specific row of a matrix.
377
+ */
378
+ _scaleRow(row, scalar) {
379
+ for (let j = 0; j < this.cols; j++) {
380
+ let multiplied = this.multiplyFn(this.data[row][j], scalar);
381
+ if (multiplied === undefined)
382
+ multiplied = 0;
383
+ this.data[row][j] = multiplied;
384
+ }
385
+ }
386
+ /**
387
+ * The function `_addScaledRow` multiplies a row in a matrix by a scalar value and adds it to another
388
+ * row.
389
+ * @param {number} targetRow - The targetRow parameter represents the index of the row in which the
390
+ * scaled values will be added.
391
+ * @param {number} sourceRow - The sourceRow parameter represents the index of the row from which the
392
+ * values will be scaled and added to the targetRow.
393
+ * @param {number} scalar - The scalar parameter is a number that is used to scale the values in the
394
+ * source row before adding them to the target row.
395
+ */
396
+ _addScaledRow(targetRow, sourceRow, scalar) {
397
+ for (let j = 0; j < this.cols; j++) {
398
+ let multiplied = this.multiplyFn(this.data[sourceRow][j], scalar);
399
+ if (multiplied === undefined)
400
+ multiplied = 0;
401
+ const scaledValue = multiplied;
402
+ let added = this.addFn(this.data[targetRow][j], scaledValue);
403
+ if (added === undefined)
404
+ added = 0;
405
+ this.data[targetRow][j] = added;
406
+ }
24
407
  }
25
408
  }
@@ -5,8 +5,8 @@
5
5
  * @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
6
6
  * @license MIT License
7
7
  */
8
- import type { ElementCallback, IterableWithSizeOrLength } from "../../types";
9
- import { IterableElementBase } from "../base";
8
+ import type { ElementCallback, IterableWithSizeOrLength } from '../../types';
9
+ import { IterableElementBase } from '../base';
10
10
  /**
11
11
  * 1. Operations at Both Ends: Supports adding and removing elements at both the front and back of the queue. This allows it to be used as a stack (last in, first out) and a queue (first in, first out).
12
12
  * 2. Efficient Random Access: Being based on an array, it offers fast random access capability, allowing constant time access to any element.
@@ -1,5 +1,5 @@
1
- import { IterableElementBase } from "../base";
2
- import { calcMinUnitsRequired, rangeCheck } from "../../utils";
1
+ import { IterableElementBase } from '../base';
2
+ import { calcMinUnitsRequired, rangeCheck } from '../../utils';
3
3
  /**
4
4
  * 1. Operations at Both Ends: Supports adding and removing elements at both the front and back of the queue. This allows it to be used as a stack (last in, first out) and a queue (first in, first out).
5
5
  * 2. Efficient Random Access: Being based on an array, it offers fast random access capability, allowing constant time access to any element.
@@ -23,7 +23,7 @@ export class Deque extends IterableElementBase {
23
23
  * @param bucketSize - The `bucketSize` parameter is the maximum number of elements that can be
24
24
  * stored in each bucket. It determines the size of each bucket in the data structure.
25
25
  */
26
- constructor(elements = [], bucketSize = (1 << 12)) {
26
+ constructor(elements = [], bucketSize = 1 << 12) {
27
27
  super();
28
28
  let _size;
29
29
  if ('length' in elements) {
@@ -45,7 +45,7 @@ export class Deque extends IterableElementBase {
45
45
  }
46
46
  const needBucketNum = calcMinUnitsRequired(_size, this._bucketSize);
47
47
  this._bucketFirst = this._bucketLast = (this._bucketCount >> 1) - (needBucketNum >> 1);
48
- this._firstInBucket = this._lastInBucket = (this._bucketSize - _size % this._bucketSize) >> 1;
48
+ this._firstInBucket = this._lastInBucket = (this._bucketSize - (_size % this._bucketSize)) >> 1;
49
49
  for (const element of elements) {
50
50
  this.push(element);
51
51
  }
@@ -99,8 +99,7 @@ export class Deque extends IterableElementBase {
99
99
  this._bucketLast = 0;
100
100
  this._lastInBucket = 0;
101
101
  }
102
- if (this._bucketLast === this._bucketFirst &&
103
- this._lastInBucket === this._firstInBucket)
102
+ if (this._bucketLast === this._bucketFirst && this._lastInBucket === this._firstInBucket)
104
103
  this._reallocate();
105
104
  }
106
105
  this._size += 1;
@@ -166,8 +165,7 @@ export class Deque extends IterableElementBase {
166
165
  this._bucketFirst = this._bucketCount - 1;
167
166
  this._firstInBucket = this._bucketSize - 1;
168
167
  }
169
- if (this._bucketFirst === this._bucketLast &&
170
- this._firstInBucket === this._lastInBucket)
168
+ if (this._bucketFirst === this._bucketLast && this._firstInBucket === this._lastInBucket)
171
169
  this._reallocate();
172
170
  }
173
171
  this._size += 1;
@@ -766,7 +764,7 @@ export class Deque extends IterableElementBase {
766
764
  if (bucketIndex >= this._bucketCount) {
767
765
  bucketIndex -= this._bucketCount;
768
766
  }
769
- indexInBucket = (overallIndex + 1) % this._bucketSize - 1;
767
+ indexInBucket = ((overallIndex + 1) % this._bucketSize) - 1;
770
768
  if (indexInBucket < 0) {
771
769
  indexInBucket = this._bucketSize - 1;
772
770
  }
@@ -4,7 +4,7 @@
4
4
  * @class
5
5
  */
6
6
  import type { ElementCallback } from '../../types';
7
- import { IterableElementBase } from "../base";
7
+ import { IterableElementBase } from '../base';
8
8
  import { SinglyLinkedList } from '../linked-list';
9
9
  /**
10
10
  * 1. First In, First Out (FIFO): The core feature of a queue is its first in, first out nature. The element added to the queue first will be the one to be removed first.
@@ -1,4 +1,4 @@
1
- import { IterableElementBase } from "../base";
1
+ import { IterableElementBase } from '../base';
2
2
  import { SinglyLinkedList } from '../linked-list';
3
3
  /**
4
4
  * 1. First In, First Out (FIFO): The core feature of a queue is its first in, first out nature. The element added to the queue first will be the one to be removed first.
@@ -1,9 +1,9 @@
1
1
  import { BinaryTree, BinaryTreeNode } from '../data-structures';
2
- import { BinaryTreeDeleteResult, BinaryTreeNested, BinaryTreeNodeNested, BinaryTreeOptions, BTNCallback, BTNExemplar } from '../types';
2
+ import { BinaryTreeDeleteResult, BinaryTreeNested, BinaryTreeNodeNested, BinaryTreeOptions, BTNCallback, KeyOrNodeOrEntry } from '../types';
3
3
  export interface IBinaryTree<K = number, V = any, N extends BinaryTreeNode<K, V, N> = BinaryTreeNodeNested<K, V>, TREE extends BinaryTree<K, V, N, TREE> = BinaryTreeNested<K, V, N>> {
4
4
  createNode(key: K, value?: N['value']): N;
5
5
  createTree(options?: Partial<BinaryTreeOptions<K>>): TREE;
6
- add(keyOrNodeOrEntry: BTNExemplar<K, V, N>, value?: V, count?: number): N | null | undefined;
7
- addMany(nodes: Iterable<BTNExemplar<K, V, N>>, values?: Iterable<V | undefined>): (N | null | undefined)[];
6
+ add(keyOrNodeOrEntry: KeyOrNodeOrEntry<K, V, N>, value?: V, count?: number): boolean;
7
+ addMany(nodes: Iterable<KeyOrNodeOrEntry<K, V, N>>, values?: Iterable<V | undefined>): boolean[];
8
8
  delete<C extends BTNCallback<N>>(identifier: ReturnType<C> | null, callback: C): BinaryTreeDeleteResult<N>[];
9
9
  }
@@ -1,6 +1,6 @@
1
1
  export declare enum BSTVariant {
2
- MIN = "MIN",
3
- MAX = "MAX"
2
+ STANDARD = "STANDARD",
3
+ INVERSE = "INVERSE"
4
4
  }
5
5
  export declare enum CP {
6
6
  lt = "lt",
@@ -44,7 +44,7 @@ export type BinaryTreePrintOptions = {
44
44
  };
45
45
  export type BTNEntry<K, V> = [K | null | undefined, V | undefined];
46
46
  export type BTNKeyOrNode<K, N> = K | null | undefined | N;
47
- export type BTNExemplar<K, V, N> = BTNEntry<K, V> | BTNKeyOrNode<K, N>;
47
+ export type KeyOrNodeOrEntry<K, V, N> = BTNEntry<K, V> | BTNKeyOrNode<K, N>;
48
48
  export type BTNodePureKeyOrNode<K, N> = K | N;
49
49
  export type BTNodePureExemplar<K, V, N> = [K, V | undefined] | BTNodePureKeyOrNode<K, N>;
50
50
  export type BSTNKeyOrNode<K, N> = K | undefined | N;
@@ -1,7 +1,7 @@
1
1
  export var BSTVariant;
2
2
  (function (BSTVariant) {
3
- BSTVariant["MIN"] = "MIN";
4
- BSTVariant["MAX"] = "MAX";
3
+ BSTVariant["STANDARD"] = "STANDARD";
4
+ BSTVariant["INVERSE"] = "INVERSE";
5
5
  })(BSTVariant || (BSTVariant = {}));
6
6
  export var CP;
7
7
  (function (CP) {
@@ -1,4 +1,4 @@
1
- import { IterableElementBase, IterableEntryBase } from "../../../data-structures";
1
+ import { IterableElementBase, IterableEntryBase } from '../../../data-structures';
2
2
  export type EntryCallback<K, V, R> = (value: V, key: K, index: number, container: IterableEntryBase<K, V>) => R;
3
3
  export type ElementCallback<V, R> = (element: V, index: number, container: IterableElementBase<V>) => R;
4
4
  export type ReduceEntryCallback<K, V, R> = (accumulator: R, value: V, key: K, index: number, container: IterableEntryBase<K, V>) => R;
@@ -1,4 +1,4 @@
1
- import { Comparator } from "../../common";
1
+ import { Comparator } from '../../common';
2
2
  export type HeapOptions<T> = {
3
3
  comparator: Comparator<T>;
4
4
  };
@@ -1,2 +1,2 @@
1
- import { HeapOptions } from "../heap";
1
+ import { HeapOptions } from '../heap';
2
2
  export type PriorityQueueOptions<T> = HeapOptions<T> & {};
@@ -22,3 +22,4 @@ export declare const rangeCheck: (index: number, min: number, max: number, messa
22
22
  export declare const throwRangeError: (message?: string) => void;
23
23
  export declare const isWeakKey: (input: unknown) => input is object;
24
24
  export declare const calcMinUnitsRequired: (totalQuantity: number, unitSize: number) => number;
25
+ export declare const roundFixed: (num: number, digit?: number) => number;
@@ -64,3 +64,7 @@ export const isWeakKey = (input) => {
64
64
  return (inputType === 'object' && input !== null) || inputType === 'function';
65
65
  };
66
66
  export const calcMinUnitsRequired = (totalQuantity, unitSize) => Math.floor((totalQuantity + unitSize - 1) / unitSize);
67
+ export const roundFixed = (num, digit = 10) => {
68
+ const multiplier = Math.pow(10, digit);
69
+ return Math.round(num * multiplier) / multiplier;
70
+ };