@raikuxq/alg-ds 3.0.2 → 4.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/lib/index.d.ts CHANGED
@@ -31,6 +31,7 @@ export type TypeArrayMatrix = Array<Array<number>>;
31
31
  */
32
32
  export declare const transposeMatrix: (matrix: TypeArrayMatrix) => TypeArrayMatrix;
33
33
  export interface IGraph<T> extends Iterable<T> {
34
+ readonly adjacencyList: ReadonlyMap<T, ReadonlySet<T>>;
34
35
  weight(): number;
35
36
  vertices(): Array<T>;
36
37
  verticesCount(): number;
@@ -38,7 +39,8 @@ export interface IGraph<T> extends Iterable<T> {
38
39
  addVertex(data: T): this;
39
40
  removeVertex(data: T): this;
40
41
  hasVertex(data: T): boolean;
41
- getVertexNeighbors(data: T): Array<T>;
42
+ getVertexKey(data: T): string;
43
+ getVertexNeighbors(data: T): Set<T>;
42
44
  addEdge(from: T, to: T, weight?: number): this;
43
45
  removeEdge(from: T, to: T): this;
44
46
  hasEdge(from: T, to: T): boolean;
@@ -269,7 +271,7 @@ export declare const presenterAdjacencyMatrix: <T>(graph: IGraph<T>) => TypeArra
269
271
  * - Maria [Bob, John]
270
272
  * - John [Maria]
271
273
  **/
272
- export declare const presenterAdjacencyLists: <T>(graph: IGraph<T>) => Map<T, Array<T>>;
274
+ export declare const presenterAdjacencyLists: <T>(graph: IGraph<T>) => ReadonlyMap<T, ReadonlySet<T>>;
273
275
  export declare enum EnumLinkedListType {
274
276
  DOUBLE = "Double linked list",
275
277
  SINGLE = "Single linked list"
@@ -340,6 +342,20 @@ export declare const createGraph: <T>(type: EnumGraphType) => IGraph<T>;
340
342
  * Creates a graph from N*N matrix that contains 1 in case of edge exists or 0 in case it does not
341
343
  */
342
344
  export declare const createGraphFromMatrix: <T>(matrix: TypeArrayMatrix, fieldsList: Array<T>, type: EnumGraphType) => IGraph<T>;
345
+ /**
346
+ * Performs a topological sort on a Directed Acyclic Graph (DAG).
347
+ *
348
+ * @template T
349
+ * @param {IGraph<T>} graph - The graph instance to sort.
350
+ * @returns {Array<T>} An array of vertices in topological order.
351
+ * @throws {IllegalStateException} When a cycle is detected in the graph.
352
+ */
353
+ export declare const topologicalSort: <T>(graph: IGraph<T>) => Array<T>;
354
+ /**
355
+ * Check is graph Directed Acyclic Graph
356
+ * @param graph
357
+ */
358
+ export declare const isDirectedAcyclicGraph: <T>(graph: IGraph<T>) => boolean;
343
359
  /**
344
360
  * FIFO data structure
345
361
  */
@@ -1028,20 +1044,29 @@ declare class GraphEdge<T> {
1028
1044
  get weight(): number;
1029
1045
  set weight(value: number);
1030
1046
  }
1031
- declare abstract class AbstractGraph<T> {
1047
+ export type TKeySelector<T> = (item: T) => string;
1048
+ export type TGraphConstructorParams<T> = {
1049
+ customKeySelector?: TKeySelector<T>;
1050
+ };
1051
+ declare abstract class AbstractGraph<T> implements IGraph<T> {
1052
+ protected static readonly EDGE_KEY_SEPARATOR: string;
1032
1053
  protected _vertices: Map<T, Set<T>>;
1033
1054
  protected _edges: Map<string, GraphEdge<T>>;
1034
1055
  /**
1035
1056
  * Created empty instance
1036
1057
  */
1037
- protected constructor();
1038
- protected static readonly EDGE_KEY_SEPARATOR: string;
1058
+ protected constructor(params?: TGraphConstructorParams<T>);
1059
+ /**
1060
+ * Get edge identifier from type
1061
+ * @example { id: 'abcd123', name: 'Maria' } => 'abcd123'
1062
+ */
1063
+ protected readonly keySelector: (vertex: T) => string;
1039
1064
  /**
1040
1065
  * Get edge key string from_to
1041
1066
  * @example Bob_Maria
1042
1067
  * @example Maria_Bob
1043
1068
  */
1044
- protected getEdgeKey(from: T, to: T): string;
1069
+ protected abstract getEdgeKey(from: T, to: T): string;
1045
1070
  /**
1046
1071
  * Find edge by its from and to vertices
1047
1072
  */
@@ -1067,6 +1092,10 @@ declare abstract class AbstractGraph<T> {
1067
1092
  * Will remove all vertices edges with vertex to remove
1068
1093
  */
1069
1094
  protected cascadeRemoveVertexEdges(vertexToRemove: T): void;
1095
+ /**
1096
+ * Get edge key by vertex value
1097
+ */
1098
+ getVertexKey(vertex: T): string;
1070
1099
  /**
1071
1100
  * Get sum of all graph edges
1072
1101
  */
@@ -1103,8 +1132,9 @@ declare abstract class AbstractGraph<T> {
1103
1132
  abstract removeEdge(from: T, to: T): this;
1104
1133
  /**
1105
1134
  * Get vertex neighbors by its data
1135
+ * @throws {IsNotFoundException} when vertex is already does not exist
1106
1136
  */
1107
- getVertexNeighbors(data: T): Array<T>;
1137
+ getVertexNeighbors(data: T): Set<T>;
1108
1138
  /**
1109
1139
  * Check if graph has vertex
1110
1140
  */
@@ -1117,6 +1147,10 @@ declare abstract class AbstractGraph<T> {
1117
1147
  * Get edge weight between from and to vertices
1118
1148
  */
1119
1149
  getEdgeWeight(from: T, to: T): number;
1150
+ /**
1151
+ * Raw adjacency list
1152
+ */
1153
+ get adjacencyList(): Map<T, Set<T>>;
1120
1154
  /**
1121
1155
  * Iterator
1122
1156
  */
@@ -1130,7 +1164,11 @@ export declare class DirectedGraph<T> extends AbstractGraph<T> {
1130
1164
  /**
1131
1165
  * @inheritDoc
1132
1166
  */
1133
- constructor();
1167
+ constructor(params?: TGraphConstructorParams<T>);
1168
+ /**
1169
+ * @inheritDoc
1170
+ */
1171
+ protected getEdgeKey(from: T, to: T): string;
1134
1172
  /**
1135
1173
  * @inheritDoc
1136
1174
  * @throws {IsNotFoundException} when vertex was not found
@@ -1159,7 +1197,10 @@ export declare class UndirectedGraph<T> extends AbstractGraph<T> {
1159
1197
  /**
1160
1198
  * @inheritDoc
1161
1199
  */
1162
- constructor();
1200
+ constructor(params?: TGraphConstructorParams<T>);
1201
+ /**
1202
+ * @inheritDoc
1203
+ */
1163
1204
  protected getEdgeKey(from: T, to: T): string;
1164
1205
  /**
1165
1206
  * @inheritDoc
package/lib/index.mjs CHANGED
@@ -1 +1 @@
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},E=(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},y=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=y(t),r=u(s);return E(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 B{_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 S{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 T extends S{queue;constructor(t){super(t),this.queue=new B}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 P{_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 C extends S{stack;constructor(t){super(t),this.stack=new P}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 A{_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 q extends S{costs;queue;constructor(t){super(t),this.costs=/* @__PURE__ */new Map,this.queue=new A}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 T(t);case L.DFS:return new C(t);case L.DIJKSTRA:return new q(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},U=({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)},j=t=>t.vertices().reduce((e,s)=>{const r=t.getVertexNeighbors(s);return e.set(s,r),e},/* @__PURE__ */new Map);var G=/* @__PURE__ */(t=>(t.DOUBLE="Double linked list",t.SINGLE="Single linked list",t))(G||{});class z 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 z(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 Q 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 W 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 H=(t,e=!1,s)=>{let r;if(e)switch(t){case G.DOUBLE:r=new Q(s);break;case G.SINGLE:r=new W(s)}else switch(t){case G.DOUBLE:r=new D(s);break;case G.SINGLE:r=new $(s)}return r};var Y=/* @__PURE__ */(t=>(t.BST="Binary Search Tree",t.RANDOMIZED_BST="Randomized Binary Search Tree",t))(Y||{}),J=/* @__PURE__ */(t=>(t.IN_ORDER="IN_ORDER",t.PRE_ORDER="PRE_ORDER",t.POST_ORDER="POST_ORDER",t))(J||{});class Z{compare=(t,e)=>t>e;_head;_length;constructor(t){t&&(this.compare=t),this._head=null,this._length=0}length(){return this._length}}class X{_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 X{_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 Z{_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 B,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 J.IN_ORDER:this.storeInOrder(r,s);break;case J.PRE_ORDER:this.storePreOrder(r,s);break;case J.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 Y.BST:e=new et;break;case Y.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;var ft=/* @__PURE__ */(t=>(t.QUICK="QUICK",t.MERGE="MERGE",t.SELECTION="SELECTION",t.BUBBLE="BUBBLE",t.INSERTION="INSERTION",t))(ft||{}),xt=/* @__PURE__ */(t=>(t.NUMBERS="NUMBERS",t.HASH="HASH",t))(xt||{});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,Y as EnumBinarySearchTreeType,L as EnumGraphTraversalType,d as EnumGraphType,G as EnumLinkedListType,xt as EnumRandomGenerationFormat,ft as EnumSortType,J as EnumTreeTraversalType,T as GraphIteratorBFS,C as GraphIteratorDFS,q as GraphIteratorDijkstra,o as IllegalArgumentException,c as IllegalStateException,k as IndexOutOfBoundsException,g as IsAlreadyExistsException,p as IsNotFoundException,Q as IterableDoubleLinkedList,W as IterableSingleLinkedList,A as PriorityQueue,B as Queue,rt as RandBinarySearchTree,$ as SingleLinkedList,P as Stack,w as UndirectedGraph,N as ValueOutOfRangeException,a as binarySearch,nt as bubbleSort,it as createBinaryTree,m as createGraph,E as createGraphFromMatrix,M as createGraphIterator,H 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,j as presenterAdjacencyLists,y as presenterAdjacencyMatrix,pt as quickSort,_t as randomizeNumberInRange,gt as roundNumber,lt as selectSort,U as shortestPath,ht as swapArrayItems,v as transposeDirectedGraph,u 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),n=t=>t>1?n(t-1)+n(t-2):t,h=s(t=>t>1?h(t-1)+h(t-2):t),a=(t,e)=>{let s=0,r=t.length-1;for(;s<=r;){const i=Math.floor(s+(r-s)/2),n=t[i];if(e===n)return i;n>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 _{static EDGE_KEY_SEPARATOR="_";_vertices;_edges;constructor(t){this._vertices=/* @__PURE__ */new Map,this._edges=/* @__PURE__ */new Map,this.keySelector=t?.customKeySelector??(t=>String(t))}keySelector;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)}getVertexKey(t){return this.keySelector(t)}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._vertices.get(t);if(e)return e;throw new p("Vertex neighbors was not found")}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}get adjacencyList(){return this._vertices}*[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 w extends _{constructor(t){super(t)}getEdgeKey(t,e){const s=this.keySelector(t),r=this.keySelector(e);return s+_.EDGE_KEY_SEPARATOR+r}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),n=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(n,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 x extends _{constructor(t){super(t)}getEdgeKey(t,e){const s=this.keySelector(t),r=this.keySelector(e);return r>s?s+x.EDGE_KEY_SEPARATOR+r:r+x.EDGE_KEY_SEPARATOR+s}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),n=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(n,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 w;break;case d.UNDIRECTED:e=new x}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,n)=>{if(1===t){const t=e[i],h=e[n];s===d.UNDIRECTED&&(r.hasEdge(t,h)||r.hasEdge(h,t))||r.addEdge(t,h)}})}),r},E=t=>{const e=t.vertices(),s=e.length,r=/* @__PURE__ */new Map;e.forEach((t,e)=>r.set(t,e));const i=Array.from({length:s},()=>new Array(s).fill(0));for(const[n,h]of t.adjacencyList){const t=r.get(n);if(void 0!==t)for(const e of h){const s=r.get(e);void 0!==s&&(i[t][s]=1)}}return i},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 k extends c{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,k.prototype)}}class R extends o{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,R.prototype)}}class b{_capacity;_length;_head;_tail;constructor(t){this._capacity=b.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 k("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 k("List is empty");if(e)throw new R("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 R("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 k("head does not exist");return this._head.data}peekFromStart(){if(this.isEmpty()||!this._tail)throw new k("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 V{_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 V{_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 S extends b{_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 D{_list;constructor(t){this._list=new S(t)}peek(){if(this.isEmpty())throw new k("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 k("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 B extends T{queue;constructor(t){super(t),this.queue=new D}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 P{_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 k("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 k("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 C extends T{stack;constructor(t){super(t),this.stack=new P}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 k("Cannot peek when heap is empty");return this._heap[0]}insert(t){this._heap.push(t),this.bubbleUp()}extractMin(){if(this.isEmpty())throw new k("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 L{_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 L}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 q=/* @__PURE__ */(t=>(t.BFS="Breadth first traversal",t.DFS="Deep first traversal",t.DIJKSTRA="Dijkstra traversal",t))(q||{});const M=(t,e)=>{switch(e){case q.BFS:return new B(t);case q.DFS:return new C(t);case q.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.adjacencyList;var G=/* @__PURE__ */(t=>(t.DOUBLE="Double linked list",t.SINGLE="Single linked list",t))(G||{});class z extends V{constructor(t,e=null){super(t,e)}}class Q extends b{_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 z(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 S{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 H extends Q{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 G.DOUBLE:r=new W(s);break;case G.SINGLE:r=new H(s)}else switch(t){case G.DOUBLE:r=new S(s);break;case G.SINGLE:r=new Q(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 ${_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 ${_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 k("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 D,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},nt=t=>{const e=[],s=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map,i=t.adjacencyList;if(t instanceof x)throw new c("Topological sort is not defined for undirected graphs");const n=i=>{if(r.get(i))throw new c("Cycle detected: topological sort is only possible for DAGs");if(s.get(i))return;s.set(i,!0),r.set(i,!0);const h=t.getVertexNeighbors(i);for(const t of h)n(t);r.set(i,!1),e.push(i)};for(const h of i.keys())s.get(h)||n(h);return e.reverse()},ht=t=>{try{return t instanceof w&&(nt(t),!0)}catch(e){if(e instanceof c)return!1;throw e}},at=(t,e,s)=>{if(e!==s){const r=t[e];t[e]=t[s],t[s]=r}},ot=t=>{for(let e=0;e<t.length-1;e++)for(let s=0;s<t.length-1;s++)t[s]>t[s+1]&&at(t,s,s+1);return t},lt=t=>t.reduce((e,s,r)=>s<t[e]?r:e,0),ut=(t,e)=>e+lt(t.slice(e)),dt=t=>{for(let e=0;e<t.length;e++){const s=ut(t,e);at(t,s,e)}return t},ct=(t,e,s)=>{if(s>e){const r=Math.floor(e+(s-e)/2);ct(t,e,r),ct(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)}},pt=t=>(ct(t,0,t.length-1),t),gt=t=>{for(let e=1;e<t.length;e++){const s=t[e];let r=e-1;for(;r>=0&&t[r]>s;)at(t,r+1,r),r--;t[r+1]=s}return t},_t=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&&(at(t,i,n),n--,i++)}return i})(t,s,r);e(t,s,i-1),e(t,i,r)}return t};return e(t)},ft=(t,e=3)=>Math.round(t*10**e)/10**e,wt=(t,e)=>Math.floor(Math.random()*(e-t))+t;var xt=/* @__PURE__ */(t=>(t.QUICK="QUICK",t.MERGE="MERGE",t.SELECTION="SELECTION",t.BUBBLE="BUBBLE",t.INSERTION="INSERTION",t))(xt||{}),mt=/* @__PURE__ */(t=>(t.NUMBERS="NUMBERS",t.HASH="HASH",t))(mt||{});export{F as BinaryHeap,et as BinarySearchTree,k as CollectionIsEmptyException,I as CollectionIsFullException,w as DirectedGraph,S as DoubleLinkedList,t as EDGE_EXISTS_STATE,e as EDGE_NOT_EXISTS_STATE,J as EnumBinarySearchTreeType,q as EnumGraphTraversalType,d as EnumGraphType,G as EnumLinkedListType,mt as EnumRandomGenerationFormat,xt as EnumSortType,Z as EnumTreeTraversalType,B as GraphIteratorBFS,C as GraphIteratorDFS,A as GraphIteratorDijkstra,o as IllegalArgumentException,c as IllegalStateException,R as IndexOutOfBoundsException,g as IsAlreadyExistsException,p as IsNotFoundException,W as IterableDoubleLinkedList,H as IterableSingleLinkedList,L as PriorityQueue,D as Queue,rt as RandBinarySearchTree,Q as SingleLinkedList,P as Stack,x as UndirectedGraph,N as ValueOutOfRangeException,a as binarySearch,ot as bubbleSort,it as createBinaryTree,m as createGraph,y as createGraphFromMatrix,M as createGraphIterator,Y as createLinkedList,r as factorial,n as fibonacci,lt as getMinIndex,ut as getMinIndexFromIndex,K as hasPath,gt as insertionSort,ht as isDirectedAcyclicGraph,s as memoize,i as memoizedFactorial,h as memoizedFibonacci,pt as mergeSort,U as presenterAdjacencyLists,E as presenterAdjacencyMatrix,_t as quickSort,wt as randomizeNumberInRange,ft as roundNumber,dt as selectSort,j as shortestPath,at as swapArrayItems,nt as topologicalSort,v as transposeDirectedGraph,u as transposeMatrix};
package/package.json CHANGED
@@ -3,6 +3,9 @@
3
3
  "scripts": {
4
4
  "test": "jest",
5
5
  "dev": "nodemon --exec tsx src/index.ts",
6
+ "demo": "nodemon --exec tsx demo/index.ts",
7
+ "benchmark:graph": "nodemon --exec tsx benchmarks/benchmark.graph.ts",
8
+ "benchmark:bst": "nodemon --exec tsx benchmarks/benchmark.bst.ts",
6
9
  "build:lib": "rimraf ./lib && vite build",
7
10
  "build:dts": "dts-bundle-generator -o lib/index.d.ts src/index.ts --no-check --inline-declare-externals false --external-inlines @babel/types",
8
11
  "build:full": "yarn build:lib && yarn build:dts",
@@ -12,6 +15,11 @@
12
15
  "docs:dev": "vuepress dev docs",
13
16
  "docs:build": "vuepress build docs"
14
17
  },
18
+ "author": {
19
+ "email": "raikuxqt@gmail.com",
20
+ "name": "raikuxq"
21
+ },
22
+ "license": "MIT",
15
23
  "repository": {
16
24
  "type": "git",
17
25
  "url": "https://github.com/raikuxq/lab-ts-algorithms"
@@ -74,6 +82,6 @@
74
82
  "vuepress": "^2.0.0-beta.48"
75
83
  },
76
84
  "dependencies": {},
77
- "version": "3.0.2",
85
+ "version": "4.0.0",
78
86
  "sideEffects": false
79
87
  }