From d44788bea910ef2d057cc885bc6857c0b8075112 Mon Sep 17 00:00:00 2001 From: Revone Date: Mon, 30 Oct 2023 18:27:58 +0800 Subject: [PATCH] [graph] Modify the data structure design of the graph to change the generics of Vertex and Edge to defaults, where it is possible to only pass the value types of Vertex and Edge for increased usability. --- src/data-structures/graph/abstract-graph.ts | 268 +++++++++--------- src/data-structures/graph/directed-graph.ts | 179 ++++++------ src/data-structures/graph/map-graph.ts | 37 ++- src/data-structures/graph/undirected-graph.ts | 110 +++---- src/data-structures/queue/queue.ts | 2 +- src/interfaces/graph.ts | 6 +- .../graph/directed-graph.test.ts | 35 ++- .../data-structures/graph/map-graph.test.ts | 46 +-- .../graph/undirected-graph.test.ts | 4 +- test/unit/data-structures/queue/queue.test.ts | 16 +- 10 files changed, 357 insertions(+), 346 deletions(-) diff --git a/src/data-structures/graph/abstract-graph.ts b/src/data-structures/graph/abstract-graph.ts index d7d5b08..5b0aa79 100644 --- a/src/data-structures/graph/abstract-graph.ts +++ b/src/data-structures/graph/abstract-graph.ts @@ -45,29 +45,29 @@ export abstract class AbstractVertex { } } -export abstract class AbstractEdge { +export abstract class AbstractEdge { /** * The above function is a protected constructor that initializes the weight, value, and hash code properties of an * object. * @param {number} [weight] - The `weight` parameter is an optional number that represents the weight of the object. If * a value is provided, it will be assigned to the `_weight` property. If no value is provided, the default value of 1 * will be assigned. - * @param {V} [val] - The `val` parameter is of type `V`, which means it can be any type. It is an optional parameter, + * @param {VO} [val] - The `val` parameter is of type `VO`, which means it can be any type. It is an optional parameter, * meaning it can be omitted when creating an instance of the class. */ - protected constructor(weight?: number, val?: V) { + protected constructor(weight?: number, val?: VO) { this._weight = weight !== undefined ? weight : 1; this._val = val; this._hashCode = uuidV4(); } - private _val: V | undefined; + private _val: VO | undefined; - get val(): V | undefined { + get val(): VO | undefined { return this._val; } - set val(value: V | undefined) { + set val(value: VO | undefined) { this._val = value; } @@ -103,13 +103,15 @@ export abstract class AbstractEdge { } export abstract class AbstractGraph< - V extends AbstractVertex = AbstractVertex, - E extends AbstractEdge = AbstractEdge -> implements IGraph + V = any, + E = any, + VO extends AbstractVertex = AbstractVertex, + EO extends AbstractEdge = AbstractEdge +> implements IGraph { - private _vertices: Map = new Map(); + private _vertices: Map = new Map(); - get vertices(): Map { + get vertices(): Map { return this._vertices; } @@ -119,7 +121,7 @@ export abstract class AbstractGraph< * @param key * @param val */ - abstract createVertex(key: VertexKey, val?: V): V; + abstract createVertex(key: VertexKey, val?: V): VO; /** * In TypeScript, a subclass inherits the interface implementation of its parent class, without needing to implement the same interface again in the subclass. This behavior differs from Java's approach. In Java, if a parent class implements an interface, the subclass needs to explicitly implement the same interface, even if the parent class has already implemented it. @@ -129,21 +131,21 @@ export abstract class AbstractGraph< * @param weight * @param val */ - abstract createEdge(srcOrV1: VertexKey | string, destOrV2: VertexKey | string, weight?: number, val?: E): E; + abstract createEdge(srcOrV1: VertexKey | string, destOrV2: VertexKey | string, weight?: number, val?: E): EO; - abstract deleteEdge(edge: E): E | null; + abstract deleteEdge(edge: EO): EO | null; - abstract getEdge(srcOrKey: V | VertexKey, destOrKey: V | VertexKey): E | null; + abstract getEdge(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | null; - abstract degreeOf(vertexOrKey: V | VertexKey): number; + abstract degreeOf(vertexOrKey: VO | VertexKey): number; - abstract edgeSet(): E[]; + abstract edgeSet(): EO[]; - abstract edgesOf(vertexOrKey: V | VertexKey): E[]; + abstract edgesOf(vertexOrKey: VO | VertexKey): EO[]; - abstract getNeighbors(vertexOrKey: V | VertexKey): V[]; + abstract getNeighbors(vertexOrKey: VO | VertexKey): VO[]; - abstract getEndsOfEdge(edge: E): [V, V] | null; + abstract getEndsOfEdge(edge: EO): [VO, VO] | null; /** * The function "getVertex" returns the vertex with the specified ID or null if it doesn't exist. @@ -152,25 +154,25 @@ export abstract class AbstractGraph< * @returns The method `getVertex` returns the vertex with the specified `vertexKey` if it exists in the `_vertices` * map. If the vertex does not exist, it returns `null`. */ - getVertex(vertexKey: VertexKey): V | null { + getVertex(vertexKey: VertexKey): VO | null { return this._vertices.get(vertexKey) || null; } /** * The function checks if a vertex exists in a graph. - * @param {V | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`V`) or a vertex ID + * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID * (`VertexKey`). * @returns a boolean value. */ - hasVertex(vertexOrKey: V | VertexKey): boolean { + hasVertex(vertexOrKey: VO | VertexKey): boolean { return this._vertices.has(this._getVertexKey(vertexOrKey)); } - addVertex(vertex: V): boolean; + addVertex(vertex: VO): boolean; - addVertex(key: VertexKey, val?: V['val']): boolean; + addVertex(key: VertexKey, val?: V): boolean; - addVertex(keyOrVertex: VertexKey | V, val?: V['val']): boolean { + addVertex(keyOrVertex: VertexKey | VO, val?: V): boolean { if (keyOrVertex instanceof AbstractVertex) { return this._addVertexOnly(keyOrVertex); } else { @@ -181,23 +183,23 @@ export abstract class AbstractGraph< /** * The `deleteVertex` function removes a vertex from a graph by its ID or by the vertex object itself. - * @param {V | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`V`) or a vertex ID + * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID * (`VertexKey`). * @returns The method is returning a boolean value. */ - deleteVertex(vertexOrKey: V | VertexKey): boolean { + deleteVertex(vertexOrKey: VO | VertexKey): boolean { const vertexKey = this._getVertexKey(vertexOrKey); return this._vertices.delete(vertexKey); } /** * The function removes all vertices from a graph and returns a boolean indicating if any vertices were removed. - * @param {V[] | VertexKey[]} vertices - The `vertices` parameter can be either an array of vertices (`V[]`) or an array + * @param {VO[] | VertexKey[]} vertices - The `vertices` parameter can be either an array of vertices (`VO[]`) or an array * of vertex IDs (`VertexKey[]`). * @returns a boolean value. It returns true if at least one vertex was successfully removed, and false if no vertices * were removed. */ - removeManyVertices(vertices: V[] | VertexKey[]): boolean { + removeManyVertices(vertices: VO[] | VertexKey[]): boolean { const removed: boolean[] = []; for (const v of vertices) { removed.push(this.deleteVertex(v)); @@ -207,22 +209,22 @@ export abstract class AbstractGraph< /** * The function checks if there is an edge between two vertices and returns a boolean value indicating the result. - * @param {VertexKey | V} v1 - The parameter v1 can be either a VertexKey or a V. A VertexKey represents the unique - * identifier of a vertex in a graph, while V represents the type of the vertex object itself. - * @param {VertexKey | V} v2 - The parameter `v2` represents the second vertex in the edge. It can be either a - * `VertexKey` or a `V` type, which represents the type of the vertex. + * @param {VertexKey | VO} v1 - The parameter v1 can be either a VertexKey or a VO. A VertexKey represents the unique + * identifier of a vertex in a graph, while VO represents the type of the vertex object itself. + * @param {VertexKey | VO} v2 - The parameter `v2` represents the second vertex in the edge. It can be either a + * `VertexKey` or a `VO` type, which represents the type of the vertex. * @returns A boolean value is being returned. */ - hasEdge(v1: VertexKey | V, v2: VertexKey | V): boolean { + hasEdge(v1: VertexKey | VO, v2: VertexKey | VO): boolean { const edge = this.getEdge(v1, v2); return !!edge; } - addEdge(edge: E): boolean; + addEdge(edge: EO): boolean; - addEdge(src: V | VertexKey, dest: V | VertexKey, weight?: number, val?: E['val']): boolean; + addEdge(src: VO | VertexKey, dest: VO | VertexKey, weight?: number, val?: E): boolean; - addEdge(srcOrEdge: V | VertexKey | E, dest?: V | VertexKey, weight?: number, val?: E['val']): boolean { + addEdge(srcOrEdge: VO | VertexKey | EO, dest?: VO | VertexKey, weight?: number, val?: E): boolean { if (srcOrEdge instanceof AbstractEdge) { return this._addEdgeOnly(srcOrEdge); } else { @@ -240,16 +242,16 @@ export abstract class AbstractGraph< /** * The function sets the weight of an edge between two vertices in a graph. - * @param {VertexKey | V} srcOrKey - The `srcOrKey` parameter can be either a `VertexKey` or a `V` object. It represents + * @param {VertexKey | VO} srcOrKey - The `srcOrKey` parameter can be either a `VertexKey` or a `VO` object. It represents * the source vertex of the edge. - * @param {VertexKey | V} destOrKey - The `destOrKey` parameter represents the destination vertex of the edge. It can be - * either a `VertexKey` or a vertex object `V`. + * @param {VertexKey | VO} destOrKey - The `destOrKey` parameter represents the destination vertex of the edge. It can be + * either a `VertexKey` or a vertex object `VO`. * @param {number} weight - The weight parameter represents the weight of the edge between the source vertex (srcOrKey) * and the destination vertex (destOrKey). * @returns a boolean value. If the edge exists between the source and destination vertices, the function will update * the weight of the edge and return true. If the edge does not exist, the function will return false. */ - setEdgeWeight(srcOrKey: VertexKey | V, destOrKey: VertexKey | V, weight: number): boolean { + setEdgeWeight(srcOrKey: VertexKey | VO, destOrKey: VertexKey | VO, weight: number): boolean { const edge = this.getEdge(srcOrKey, destOrKey); if (edge) { edge.weight = weight; @@ -261,20 +263,20 @@ export abstract class AbstractGraph< /** * The function `getAllPathsBetween` finds all paths between two vertices in a graph using depth-first search. - * @param {V | VertexKey} v1 - The parameter `v1` represents either a vertex object (`V`) or a vertex ID (`VertexKey`). + * @param {VO | VertexKey} v1 - The parameter `v1` represents either a vertex object (`VO`) or a vertex ID (`VertexKey`). * It is the starting vertex for finding paths. - * @param {V | VertexKey} v2 - The parameter `v2` represents either a vertex object (`V`) or a vertex ID (`VertexKey`). - * @returns The function `getAllPathsBetween` returns an array of arrays of vertices (`V[][]`). + * @param {VO | VertexKey} v2 - The parameter `v2` represents either a vertex object (`VO`) or a vertex ID (`VertexKey`). + * @returns The function `getAllPathsBetween` returns an array of arrays of vertices (`VO[][]`). */ - getAllPathsBetween(v1: V | VertexKey, v2: V | VertexKey): V[][] { - const paths: V[][] = []; + getAllPathsBetween(v1: VO | VertexKey, v2: VO | VertexKey): VO[][] { + const paths: VO[][] = []; const vertex1 = this._getVertex(v1); const vertex2 = this._getVertex(v2); if (!(vertex1 && vertex2)) { return []; } - const dfs = (cur: V, dest: V, visiting: Map, path: V[]) => { + const dfs = (cur: VO, dest: VO, visiting: Map, path: VO[]) => { visiting.set(cur, true); if (cur === dest) { @@ -286,23 +288,23 @@ export abstract class AbstractGraph< if (!visiting.get(neighbor)) { path.push(neighbor); dfs(neighbor, dest, visiting, path); - arrayRemove(path, (vertex: V) => vertex === neighbor); + arrayRemove(path, (vertex: VO) => vertex === neighbor); } } visiting.set(cur, false); }; - dfs(vertex1, vertex2, new Map(), []); + dfs(vertex1, vertex2, new Map(), []); return paths; } /** * The function calculates the sum of weights along a given path. - * @param {V[]} path - An array of vertices (V) representing a path in a graph. + * @param {VO[]} path - An array of vertices (VO) representing a path in a graph. * @returns The function `getPathSumWeight` returns the sum of the weights of the edges in the given path. */ - getPathSumWeight(path: V[]): number { + getPathSumWeight(path: VO[]): number { let sum = 0; for (let i = 0; i < path.length; i++) { sum += this.getEdge(path[i], path[i + 1])?.weight || 0; @@ -313,8 +315,8 @@ export abstract class AbstractGraph< /** * The function `getMinCostBetween` calculates the minimum cost between two vertices in a graph, either based on edge * weights or using a breadth-first search algorithm. - * @param {V | VertexKey} v1 - The parameter `v1` represents the starting vertex or its ID. - * @param {V | VertexKey} v2 - The parameter `v2` represents the destination vertex or its ID. It is the vertex to which + * @param {VO | VertexKey} v1 - The parameter `v1` represents the starting vertex or its ID. + * @param {VO | VertexKey} v2 - The parameter `v2` represents the destination vertex or its ID. It is the vertex to which * you want to find the minimum cost or weight from the source vertex `v1`. * @param {boolean} [isWeight] - isWeight is an optional parameter that indicates whether the graph edges have weights. * If isWeight is set to true, the function will calculate the minimum cost between v1 and v2 based on the weights of @@ -324,7 +326,7 @@ export abstract class AbstractGraph< * vertices. If `isWeight` is `false` or not provided, it uses a breadth-first search (BFS) algorithm to calculate the * minimum number of */ - getMinCostBetween(v1: V | VertexKey, v2: V | VertexKey, isWeight?: boolean): number | null { + getMinCostBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean): number | null { if (isWeight === undefined) isWeight = false; if (isWeight) { @@ -342,8 +344,8 @@ export abstract class AbstractGraph< return null; } - const visited: Map = new Map(); - const queue = new Queue([vertex1]); + const visited: Map = new Map(); + const queue = new Queue([vertex1]); visited.set(vertex1, true); let cost = 0; while (queue.size > 0) { @@ -372,17 +374,17 @@ export abstract class AbstractGraph< /** * The function `getMinPathBetween` returns the minimum path between two vertices in a graph, either based on weight or * using a breadth-first search algorithm. - * @param {V | VertexKey} v1 - The parameter `v1` represents the starting vertex of the path. It can be either a vertex - * object (`V`) or a vertex ID (`VertexKey`). - * @param {V | VertexKey} v2 - V | VertexKey - The second vertex or vertex ID between which we want to find the minimum + * @param {VO | VertexKey} v1 - The parameter `v1` represents the starting vertex of the path. It can be either a vertex + * object (`VO`) or a vertex ID (`VertexKey`). + * @param {VO | VertexKey} v2 - VO | VertexKey - The second vertex or vertex ID between which we want to find the minimum * path. * @param {boolean} [isWeight] - A boolean flag indicating whether to consider the weight of edges in finding the * minimum path. If set to true, the function will use Dijkstra's algorithm to find the minimum weighted path. If set * to false, the function will use breadth-first search (BFS) to find the minimum path. - * @returns The function `getMinPathBetween` returns an array of vertices (`V[]`) representing the minimum path between + * @returns The function `getMinPathBetween` returns an array of vertices (`VO[]`) representing the minimum path between * two vertices (`v1` and `v2`). If there is no path between the vertices, it returns `null`. */ - getMinPathBetween(v1: V | VertexKey, v2: V | VertexKey, isWeight?: boolean): V[] | null { + getMinPathBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean): VO[] | null { if (isWeight === undefined) isWeight = false; if (isWeight) { @@ -401,14 +403,14 @@ export abstract class AbstractGraph< return allPaths[minIndex] || null; } else { // BFS - let minPath: V[] = []; + let minPath: VO[] = []; const vertex1 = this._getVertex(v1); const vertex2 = this._getVertex(v2); if (!(vertex1 && vertex2)) { return []; } - const dfs = (cur: V, dest: V, visiting: Map, path: V[]) => { + const dfs = (cur: VO, dest: VO, visiting: Map, path: VO[]) => { visiting.set(cur, true); if (cur === dest) { @@ -421,29 +423,29 @@ export abstract class AbstractGraph< if (!visiting.get(neighbor)) { path.push(neighbor); dfs(neighbor, dest, visiting, path); - arrayRemove(path, (vertex: V) => vertex === neighbor); + arrayRemove(path, (vertex: VO) => vertex === neighbor); } } visiting.set(cur, false); }; - dfs(vertex1, vertex2, new Map(), []); + dfs(vertex1, vertex2, new Map(), []); return minPath; } } /** - * Dijkstra algorithm time: O(VE) space: O(V + E) + * Dijkstra algorithm time: O(VE) space: O(VO + EO) * / /** - * Dijkstra algorithm time: O(VE) space: O(V + E) + * Dijkstra algorithm time: O(VE) space: O(VO + EO) * The function `dijkstraWithoutHeap` implements Dijkstra's algorithm to find the shortest path between two vertices in * a graph without using a heap data structure. - * @param {V | VertexKey} src - The source vertex from which to start the Dijkstra's algorithm. It can be either a + * @param {VO | VertexKey} src - The source vertex from which to start the Dijkstra's algorithm. It can be either a * vertex object or a vertex ID. - * @param {V | VertexKey | null} [dest] - The `dest` parameter in the `dijkstraWithoutHeap` function is an optional + * @param {VO | VertexKey | null} [dest] - The `dest` parameter in the `dijkstraWithoutHeap` function is an optional * parameter that specifies the destination vertex for the Dijkstra algorithm. It can be either a vertex object or its * identifier. If no destination is provided, the value is set to `null`. * @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum @@ -452,27 +454,27 @@ export abstract class AbstractGraph< * @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate * paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the * shortest paths from the source vertex to all other vertices in the graph. If `genPaths - * @returns The function `dijkstraWithoutHeap` returns an object of type `DijkstraResult`. + * @returns The function `dijkstraWithoutHeap` returns an object of type `DijkstraResult`. */ dijkstraWithoutHeap( - src: V | VertexKey, - dest?: V | VertexKey | null, + src: VO | VertexKey, + dest?: VO | VertexKey | null, getMinDist?: boolean, genPaths?: boolean - ): DijkstraResult { + ): DijkstraResult { if (getMinDist === undefined) getMinDist = false; if (genPaths === undefined) genPaths = false; if (dest === undefined) dest = null; let minDist = Infinity; - let minDest: V | null = null; - let minPath: V[] = []; - const paths: V[][] = []; + let minDest: VO | null = null; + let minPath: VO[] = []; + const paths: VO[][] = []; const vertices = this._vertices; - const distMap: Map = new Map(); - const seen: Set = new Set(); - const preMap: Map = new Map(); // predecessor + const distMap: Map = new Map(); + const seen: Set = new Set(); + const preMap: Map = new Map(); // predecessor const srcVertex = this._getVertex(src); const destVertex = dest ? this._getVertex(dest) : null; @@ -490,7 +492,7 @@ export abstract class AbstractGraph< const getMinOfNoSeen = () => { let min = Infinity; - let minV: V | null = null; + let minV: VO | null = null; for (const [key, val] of distMap) { if (!seen.has(key)) { if (val < min) { @@ -502,12 +504,12 @@ export abstract class AbstractGraph< return minV; }; - const getPaths = (minV: V | null) => { + const getPaths = (minV: VO | null) => { for (const vertex of vertices) { const vertexOrKey = vertex[1]; if (vertexOrKey instanceof AbstractVertex) { - const path: V[] = [vertexOrKey]; + const path: VO[] = [vertexOrKey]; let parent = preMap.get(vertexOrKey); while (parent) { path.push(parent); @@ -569,11 +571,11 @@ export abstract class AbstractGraph< } /** - * Dijkstra algorithm time: O(logVE) space: O(V + E) + * Dijkstra algorithm time: O(logVE) space: O(VO + EO) * * Dijkstra's algorithm only solves the single-source shortest path problem, while the Bellman-Ford algorithm and Floyd-Warshall algorithm can address shortest paths between all pairs of nodes. * Dijkstra's algorithm is suitable for graphs with non-negative edge weights, whereas the Bellman-Ford algorithm and Floyd-Warshall algorithm can handle negative-weight edges. - * The time complexity of Dijkstra's algorithm and the Bellman-Ford algorithm depends on the size of the graph, while the time complexity of the Floyd-Warshall algorithm is O(V^3), where V is the number of nodes. For dense graphs, Floyd-Warshall might become slower. + * The time complexity of Dijkstra's algorithm and the Bellman-Ford algorithm depends on the size of the graph, while the time complexity of the Floyd-Warshall algorithm is O(VO^3), where VO is the number of nodes. For dense graphs, Floyd-Warshall might become slower. * * / @@ -581,9 +583,9 @@ export abstract class AbstractGraph< * Dijkstra's algorithm is used to find the shortest paths from a source node to all other nodes in a graph. Its basic idea is to repeatedly choose the node closest to the source node and update the distances of other nodes using this node as an intermediary. Dijkstra's algorithm requires that the edge weights in the graph are non-negative. * The `dijkstra` function implements Dijkstra's algorithm to find the shortest path between a source vertex and an * optional destination vertex, and optionally returns the minimum distance, the paths, and other information. - * @param {V | VertexKey} src - The `src` parameter represents the source vertex from which the Dijkstra algorithm will + * @param {VO | VertexKey} src - The `src` parameter represents the source vertex from which the Dijkstra algorithm will * start. It can be either a vertex object or a vertex ID. - * @param {V | VertexKey | null} [dest] - The `dest` parameter is the destination vertex or vertex ID. It specifies the + * @param {VO | VertexKey | null} [dest] - The `dest` parameter is the destination vertex or vertex ID. It specifies the * vertex to which the shortest path is calculated from the source vertex. If no destination is provided, the algorithm * will calculate the shortest paths to all other vertices from the source vertex. * @param {boolean} [getMinDist] - The `getMinDist` parameter is a boolean flag that determines whether the minimum @@ -592,26 +594,26 @@ export abstract class AbstractGraph< * @param {boolean} [genPaths] - The `genPaths` parameter is a boolean flag that determines whether or not to generate * paths in the Dijkstra algorithm. If `genPaths` is set to `true`, the algorithm will calculate and return the * shortest paths from the source vertex to all other vertices in the graph. If `genPaths - * @returns The function `dijkstra` returns an object of type `DijkstraResult`. + * @returns The function `dijkstra` returns an object of type `DijkstraResult`. */ dijkstra( - src: V | VertexKey, - dest?: V | VertexKey | null, + src: VO | VertexKey, + dest?: VO | VertexKey | null, getMinDist?: boolean, genPaths?: boolean - ): DijkstraResult { + ): DijkstraResult { if (getMinDist === undefined) getMinDist = false; if (genPaths === undefined) genPaths = false; if (dest === undefined) dest = null; let minDist = Infinity; - let minDest: V | null = null; - let minPath: V[] = []; - const paths: V[][] = []; + let minDest: VO | null = null; + let minPath: VO[] = []; + const paths: VO[][] = []; const vertices = this._vertices; - const distMap: Map = new Map(); - const seen: Set = new Set(); - const preMap: Map = new Map(); // predecessor + const distMap: Map = new Map(); + const seen: Set = new Set(); + const preMap: Map = new Map(); // predecessor const srcVertex = this._getVertex(src); const destVertex = dest ? this._getVertex(dest) : null; @@ -623,7 +625,7 @@ export abstract class AbstractGraph< if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Infinity); } - const heap = new PriorityQueue<{key: number; val: V}>({comparator: (a, b) => a.key - b.key}); + const heap = new PriorityQueue<{key: number; val: VO}>({comparator: (a, b) => a.key - b.key}); heap.add({key: 0, val: srcVertex}); distMap.set(srcVertex, 0); @@ -631,14 +633,14 @@ export abstract class AbstractGraph< /** * The function `getPaths` retrieves all paths from vertices to a specified minimum vertex. - * @param {V | null} minV - The parameter `minV` is of type `V | null`. It represents the minimum vertex value or + * @param {VO | null} minV - The parameter `minV` is of type `VO | null`. It represents the minimum vertex value or * null. */ - const getPaths = (minV: V | null) => { + const getPaths = (minV: VO | null) => { for (const vertex of vertices) { const vertexOrKey = vertex[1]; if (vertexOrKey instanceof AbstractVertex) { - const path: V[] = [vertexOrKey]; + const path: VO[] = [vertexOrKey]; let parent = preMap.get(vertexOrKey); while (parent) { path.push(parent); @@ -706,17 +708,17 @@ export abstract class AbstractGraph< } /** - * BellmanFord time:O(VE) space:O(V) + * BellmanFord time:O(VE) space:O(VO) * one to rest pairs * / /** - * BellmanFord time:O(VE) space:O(V) + * BellmanFord time:O(VE) space:O(VO) * one to rest pairs * The Bellman-Ford algorithm is also used to find the shortest paths from a source node to all other nodes in a graph. Unlike Dijkstra's algorithm, it can handle edge weights that are negative. Its basic idea involves iterative relaxation of all edges for several rounds to gradually approximate the shortest paths. Due to its ability to handle negative-weight edges, the Bellman-Ford algorithm is more flexible in some scenarios. * The `bellmanFord` function implements the Bellman-Ford algorithm to find the shortest path from a source vertex to * all other vertices in a graph, and optionally detects negative cycles and generates the minimum path. - * @param {V | VertexKey} src - The `src` parameter is the source vertex from which the Bellman-Ford algorithm will + * @param {VO | VertexKey} src - The `src` parameter is the source vertex from which the Bellman-Ford algorithm will * start calculating the shortest paths. It can be either a vertex object or a vertex ID. * @param {boolean} [scanNegativeCycle] - A boolean flag indicating whether to scan for negative cycles in the graph. * @param {boolean} [getMin] - The `getMin` parameter is a boolean flag that determines whether the algorithm should @@ -726,16 +728,16 @@ export abstract class AbstractGraph< * vertex. * @returns The function `bellmanFord` returns an object with the following properties: */ - bellmanFord(src: V | VertexKey, scanNegativeCycle?: boolean, getMin?: boolean, genPath?: boolean) { + bellmanFord(src: VO | VertexKey, scanNegativeCycle?: boolean, getMin?: boolean, genPath?: boolean) { if (getMin === undefined) getMin = false; if (genPath === undefined) genPath = false; const srcVertex = this._getVertex(src); - const paths: V[][] = []; - const distMap: Map = new Map(); - const preMap: Map = new Map(); // predecessor + const paths: VO[][] = []; + const distMap: Map = new Map(); + const preMap: Map = new Map(); // predecessor let min = Infinity; - let minPath: V[] = []; + let minPath: VO[] = []; // TODO let hasNegativeCycle: boolean | undefined; if (scanNegativeCycle) hasNegativeCycle = false; @@ -770,7 +772,7 @@ export abstract class AbstractGraph< } } - let minDest: V | null = null; + let minDest: VO | null = null; if (getMin) { distMap.forEach((d, v) => { if (v !== srcVertex) { @@ -786,7 +788,7 @@ export abstract class AbstractGraph< for (const vertex of vertices) { const vertexOrKey = vertex[1]; if (vertexOrKey instanceof AbstractVertex) { - const path: V[] = [vertexOrKey]; + const path: VO[] = [vertexOrKey]; let parent = preMap.get(vertexOrKey); while (parent !== undefined) { path.push(parent); @@ -815,34 +817,34 @@ export abstract class AbstractGraph< } /** - * Dijkstra algorithm time: O(logVE) space: O(V + E) + * Dijkstra algorithm time: O(logVE) space: O(VO + EO) * / /** - * Dijkstra algorithm time: O(logVE) space: O(V + E) + * Dijkstra algorithm time: O(logVE) space: O(VO + EO) * Dijkstra's algorithm is used to find the shortest paths from a source node to all other nodes in a graph. Its basic idea is to repeatedly choose the node closest to the source node and update the distances of other nodes using this node as an intermediary. Dijkstra's algorithm requires that the edge weights in the graph are non-negative. */ /** - * BellmanFord time:O(VE) space:O(V) + * BellmanFord time:O(VE) space:O(VO) * one to rest pairs * The Bellman-Ford algorithm is also used to find the shortest paths from a source node to all other nodes in a graph. Unlike Dijkstra's algorithm, it can handle edge weights that are negative. Its basic idea involves iterative relaxation of all edges for several rounds to gradually approximate the shortest paths. Due to its ability to handle negative-weight edges, the Bellman-Ford algorithm is more flexible in some scenarios. * The `bellmanFord` function implements the Bellman-Ford algorithm to find the shortest path from a source vertex to */ /** - * Floyd algorithm time: O(V^3) space: O(V^2), not support graph with negative weight cycle + * Floyd algorithm time: O(VO^3) space: O(VO^2), not support graph with negative weight cycle * all pairs * The Floyd-Warshall algorithm is used to find the shortest paths between all pairs of nodes in a graph. It employs dynamic programming to compute the shortest paths from any node to any other node. The Floyd-Warshall algorithm's advantage lies in its ability to handle graphs with negative-weight edges, and it can simultaneously compute shortest paths between any two nodes. */ /** - * Floyd algorithm time: O(V^3) space: O(V^2), not support graph with negative weight cycle + * Floyd algorithm time: O(VO^3) space: O(VO^2), not support graph with negative weight cycle * all pairs * / /** - * Floyd algorithm time: O(V^3) space: O(V^2), not support graph with negative weight cycle + * Floyd algorithm time: O(VO^3) space: O(VO^2), not support graph with negative weight cycle * all pairs * The Floyd-Warshall algorithm is used to find the shortest paths between all pairs of nodes in a graph. It employs dynamic programming to compute the shortest paths from any node to any other node. The Floyd-Warshall algorithm's advantage lies in its ability to handle graphs with negative-weight edges, and it can simultaneously compute shortest paths between any two nodes. * The function implements the Floyd-Warshall algorithm to find the shortest path between all pairs of vertices in a @@ -852,12 +854,12 @@ export abstract class AbstractGraph< * `predecessor` property is a 2D array of vertices (or `null`) representing the predecessor vertices in the shortest * path between vertices in the */ - floyd(): {costs: number[][]; predecessor: (V | null)[][]} { + floyd(): {costs: number[][]; predecessor: (VO | null)[][]} { const idAndVertices = [...this._vertices]; const n = idAndVertices.length; const costs: number[][] = []; - const predecessor: (V | null)[][] = []; + const predecessor: (VO | null)[][] = []; // successors for (let i = 0; i < n; i++) { @@ -927,8 +929,8 @@ export abstract class AbstractGraph< if (needSCCs === undefined) needSCCs = defaultConfig; if (needCycles === undefined) needCycles = defaultConfig; - const dfnMap: Map = new Map(); - const lowMap: Map = new Map(); + const dfnMap: Map = new Map(); + const lowMap: Map = new Map(); const vertices = this._vertices; vertices.forEach(v => { dfnMap.set(v, -1); @@ -937,10 +939,10 @@ export abstract class AbstractGraph< const [root] = vertices.values(); - const articulationPoints: V[] = []; - const bridges: E[] = []; + const articulationPoints: VO[] = []; + const bridges: EO[] = []; let dfn = 0; - const dfs = (cur: V, parent: V | null) => { + const dfs = (cur: VO, parent: VO | null) => { dfn++; dfnMap.set(cur, dfn); lowMap.set(cur, dfn); @@ -983,10 +985,10 @@ export abstract class AbstractGraph< dfs(root, null); - let SCCs: Map = new Map(); + let SCCs: Map = new Map(); const getSCCs = () => { - const SCCs: Map = new Map(); + const SCCs: Map = new Map(); lowMap.forEach((low, vertex) => { if (!SCCs.has(low)) { SCCs.set(low, [vertex]); @@ -1001,9 +1003,9 @@ export abstract class AbstractGraph< SCCs = getSCCs(); } - const cycles: Map = new Map(); + const cycles: Map = new Map(); if (needCycles) { - let SCCs: Map = new Map(); + let SCCs: Map = new Map(); if (SCCs.size < 1) { SCCs = getSCCs(); } @@ -1018,9 +1020,9 @@ export abstract class AbstractGraph< return {dfnMap, lowMap, bridges, articulationPoints, SCCs, cycles}; } - protected abstract _addEdgeOnly(edge: E): boolean; + protected abstract _addEdgeOnly(edge: EO): boolean; - protected _addVertexOnly(newVertex: V): boolean { + protected _addVertexOnly(newVertex: VO): boolean { if (this.hasVertex(newVertex)) { return false; // throw (new Error('Duplicated vertex key is not allowed')); @@ -1029,16 +1031,16 @@ export abstract class AbstractGraph< return true; } - protected _getVertex(vertexOrKey: VertexKey | V): V | null { + protected _getVertex(vertexOrKey: VertexKey | VO): VO | null { const vertexKey = this._getVertexKey(vertexOrKey); return this._vertices.get(vertexKey) || null; } - protected _getVertexKey(vertexOrKey: V | VertexKey): VertexKey { + protected _getVertexKey(vertexOrKey: VO | VertexKey): VertexKey { return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey; } - protected _setVertices(value: Map) { + protected _setVertices(value: Map) { this._vertices = value; } } diff --git a/src/data-structures/graph/directed-graph.ts b/src/data-structures/graph/directed-graph.ts index 175e6bc..32e522d 100644 --- a/src/data-structures/graph/directed-graph.ts +++ b/src/data-structures/graph/directed-graph.ts @@ -23,7 +23,7 @@ export class DirectedVertex extends AbstractVertex { } } -export class DirectedEdge extends AbstractEdge { +export class DirectedEdge extends AbstractEdge { /** * The constructor function initializes the source and destination vertices of an edge, along with an optional weight * and value. @@ -32,10 +32,10 @@ export class DirectedEdge extends AbstractEdge { * @param {VertexKey} dest - The `dest` parameter represents the destination vertex of an edge. It is of type * `VertexKey`, which is likely a unique identifier for a vertex in a graph. * @param {number} [weight] - The weight parameter is an optional number that represents the weight of the edge. - * @param {V} [val] - The `val` parameter is an optional parameter of type `V`. It represents the value associated with + * @param {E} [val] - The `val` parameter is an optional parameter of type `E`. It represents the value associated with * the edge. */ - constructor(src: VertexKey, dest: VertexKey, weight?: number, val?: V) { + constructor(src: VertexKey, dest: VertexKey, weight?: number, val?: E) { super(weight, val); this._src = src; this._dest = dest; @@ -62,9 +62,14 @@ export class DirectedEdge extends AbstractEdge { } } -export class DirectedGraph = DirectedVertex, E extends DirectedEdge = DirectedEdge> - extends AbstractGraph - implements IGraph +export class DirectedGraph< + V = any, + E = any, + VO extends DirectedVertex = DirectedVertex, + EO extends DirectedEdge = DirectedEdge + > + extends AbstractGraph + implements IGraph { /** * The constructor function initializes an instance of a class. @@ -73,15 +78,15 @@ export class DirectedGraph = DirectedVertex, E ext super(); } - private _outEdgeMap: Map = new Map(); + private _outEdgeMap: Map = new Map(); - get outEdgeMap(): Map { + get outEdgeMap(): Map { return this._outEdgeMap; } - private _inEdgeMap: Map = new Map(); + private _inEdgeMap: Map = new Map(); - get inEdgeMap(): Map { + get inEdgeMap(): Map { return this._inEdgeMap; } @@ -97,10 +102,10 @@ export class DirectedGraph = DirectedVertex, E ext * @param [val] - The 'val' parameter is an optional value that can be assigned to the vertex. If a value is provided, * it will be assigned to the 'val' property of the vertex. If no value is provided, the 'val' property will be * assigned the same value as the 'key' parameter - * @returns a new instance of a DirectedVertex object, casted as type V. + * @returns a new instance of a DirectedVertex object, casted as type VO. */ - createVertex(key: VertexKey, val?: V['val']): V { - return new DirectedVertex(key, val ?? key) as V; + createVertex(key: VertexKey, val?: V): VO { + return new DirectedVertex(key, val ?? key) as VO; } /** @@ -116,26 +121,26 @@ export class DirectedGraph = DirectedVertex, E ext * weight is provided, it defaults to 1. * @param [val] - The 'val' parameter is an optional value that can be assigned to the edge. It can be of any type and * is used to store additional information or data associated with the edge. - * @returns a new instance of a DirectedEdge object, casted as type E. + * @returns a new instance of a DirectedEdge object, casted as type EO. */ - createEdge(src: VertexKey, dest: VertexKey, weight?: number, val?: E['val']): E { - return new DirectedEdge(src, dest, weight ?? 1, val) as E; + createEdge(src: VertexKey, dest: VertexKey, weight?: number, val?: E): EO { + return new DirectedEdge(src, dest, weight ?? 1, val) as EO; } /** * The `getEdge` function retrieves an edge between two vertices based on their source and destination IDs. - * @param {V | null | VertexKey} srcOrKey - The source vertex or its ID. It can be either a vertex object or a vertex ID. - * @param {V | null | VertexKey} destOrKey - The `destOrKey` parameter in the `getEdge` function represents the - * destination vertex of the edge. It can be either a vertex object (`V`), a vertex ID (`VertexKey`), or `null` if the + * @param {VO | null | VertexKey} srcOrKey - The source vertex or its ID. It can be either a vertex object or a vertex ID. + * @param {VO | null | VertexKey} destOrKey - The `destOrKey` parameter in the `getEdge` function represents the + * destination vertex of the edge. It can be either a vertex object (`VO`), a vertex ID (`VertexKey`), or `null` if the * destination is not specified. * @returns the first edge found between the source and destination vertices, or null if no such edge is found. */ - getEdge(srcOrKey: V | null | VertexKey, destOrKey: V | null | VertexKey): E | null { - let edges: E[] = []; + getEdge(srcOrKey: VO | null | VertexKey, destOrKey: VO | null | VertexKey): EO | null { + let edges: EO[] = []; if (srcOrKey !== null && destOrKey !== null) { - const src: V | null = this._getVertex(srcOrKey); - const dest: V | null = this._getVertex(destOrKey); + const src: VO | null = this._getVertex(srcOrKey); + const dest: VO | null = this._getVertex(destOrKey); if (src && dest) { const srcOutEdges = this._outEdgeMap.get(src); @@ -150,49 +155,49 @@ export class DirectedGraph = DirectedVertex, E ext /** * The function removes an edge between two vertices in a graph and returns the removed edge. - * @param {V | VertexKey} srcOrKey - The source vertex or its ID. - * @param {V | VertexKey} destOrKey - The `destOrKey` parameter represents the destination vertex or its ID. - * @returns the removed edge (E) if it exists, or null if either the source or destination vertex does not exist. + * @param {VO | VertexKey} srcOrKey - The source vertex or its ID. + * @param {VO | VertexKey} destOrKey - The `destOrKey` parameter represents the destination vertex or its ID. + * @returns the removed edge (EO) if it exists, or null if either the source or destination vertex does not exist. */ - deleteEdgeSrcToDest(srcOrKey: V | VertexKey, destOrKey: V | VertexKey): E | null { - const src: V | null = this._getVertex(srcOrKey); - const dest: V | null = this._getVertex(destOrKey); - let removed: E | null = null; + deleteEdgeSrcToDest(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | null { + const src: VO | null = this._getVertex(srcOrKey); + const dest: VO | null = this._getVertex(destOrKey); + let removed: EO | null = null; if (!src || !dest) { return null; } const srcOutEdges = this._outEdgeMap.get(src); if (srcOutEdges) { - arrayRemove(srcOutEdges, (edge: E) => edge.dest === dest.key); + arrayRemove(srcOutEdges, (edge: EO) => edge.dest === dest.key); } const destInEdges = this._inEdgeMap.get(dest); if (destInEdges) { - removed = arrayRemove(destInEdges, (edge: E) => edge.src === src.key)[0] || null; + removed = arrayRemove(destInEdges, (edge: EO) => edge.src === src.key)[0] || null; } return removed; } /** * The function removes an edge from a graph and returns the removed edge, or null if the edge was not found. - * @param {E} edge - The `edge` parameter is an object that represents an edge in a graph. It has two properties: `src` + * @param {EO} edge - The `edge` parameter is an object that represents an edge in a graph. It has two properties: `src` * and `dest`, which represent the source and destination vertices of the edge, respectively. - * @returns The method `deleteEdge` returns the removed edge (`E`) if it exists, or `null` if the edge does not exist. + * @returns The method `deleteEdge` returns the removed edge (`EO`) if it exists, or `null` if the edge does not exist. */ - deleteEdge(edge: E): E | null { - let removed: E | null = null; + deleteEdge(edge: EO): EO | null { + let removed: EO | null = null; const src = this._getVertex(edge.src); const dest = this._getVertex(edge.dest); if (src && dest) { const srcOutEdges = this._outEdgeMap.get(src); if (srcOutEdges && srcOutEdges.length > 0) { - arrayRemove(srcOutEdges, (edge: E) => edge.src === src.key); + arrayRemove(srcOutEdges, (edge: EO) => edge.src === src.key); } const destInEdges = this._inEdgeMap.get(dest); if (destInEdges && destInEdges.length > 0) { - removed = arrayRemove(destInEdges, (edge: E) => edge.dest === dest.key)[0]; + removed = arrayRemove(destInEdges, (edge: EO) => edge.dest === dest.key)[0]; } } @@ -201,14 +206,14 @@ export class DirectedGraph = DirectedVertex, E ext /** * The function removes edges between two vertices and returns the removed edges. - * @param {VertexKey | V} v1 - The parameter `v1` can be either a `VertexKey` or a `V`. A `VertexKey` represents the - * unique identifier of a vertex in a graph, while `V` represents the actual vertex object. - * @param {VertexKey | V} v2 - The parameter `v2` represents either a `VertexKey` or a `V` object. It is used to specify + * @param {VertexKey | VO} v1 - The parameter `v1` can be either a `VertexKey` or a `VO`. A `VertexKey` represents the + * unique identifier of a vertex in a graph, while `VO` represents the actual vertex object. + * @param {VertexKey | VO} v2 - The parameter `v2` represents either a `VertexKey` or a `VO` object. It is used to specify * the second vertex in the edge that needs to be removed. - * @returns an array of removed edges (E[]). + * @returns an array of removed edges (EO[]). */ - deleteEdgesBetween(v1: VertexKey | V, v2: VertexKey | V): E[] { - const removed: E[] = []; + deleteEdgesBetween(v1: VertexKey | VO, v2: VertexKey | VO): EO[] { + const removed: EO[] = []; if (v1 && v2) { const v1ToV2 = this.deleteEdgeSrcToDest(v1, v2); @@ -223,11 +228,11 @@ export class DirectedGraph = DirectedVertex, E ext /** * The function `incomingEdgesOf` returns an array of incoming edges for a given vertex or vertex ID. - * @param {V | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`V`) or a vertex ID + * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID * (`VertexKey`). - * @returns The method `incomingEdgesOf` returns an array of edges (`E[]`). + * @returns The method `incomingEdgesOf` returns an array of edges (`EO[]`). */ - incomingEdgesOf(vertexOrKey: V | VertexKey): E[] { + incomingEdgesOf(vertexOrKey: VO | VertexKey): EO[] { const target = this._getVertex(vertexOrKey); if (target) { return this.inEdgeMap.get(target) || []; @@ -237,11 +242,11 @@ export class DirectedGraph = DirectedVertex, E ext /** * The function `outgoingEdgesOf` returns an array of outgoing edges from a given vertex or vertex ID. - * @param {V | VertexKey} vertexOrKey - The parameter `vertexOrKey` can accept either a vertex object (`V`) or a vertex ID + * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can accept either a vertex object (`VO`) or a vertex ID * (`VertexKey`). - * @returns The method `outgoingEdgesOf` returns an array of edges (`E[]`). + * @returns The method `outgoingEdgesOf` returns an array of edges (`EO[]`). */ - outgoingEdgesOf(vertexOrKey: V | VertexKey): E[] { + outgoingEdgesOf(vertexOrKey: VO | VertexKey): EO[] { const target = this._getVertex(vertexOrKey); if (target) { return this._outEdgeMap.get(target) || []; @@ -251,69 +256,69 @@ export class DirectedGraph = DirectedVertex, E ext /** * The function "degreeOf" returns the total degree of a vertex, which is the sum of its out-degree and in-degree. - * @param {VertexKey | V} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `V`. + * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`. * @returns The sum of the out-degree and in-degree of the specified vertex or vertex ID. */ - degreeOf(vertexOrKey: VertexKey | V): number { + degreeOf(vertexOrKey: VertexKey | VO): number { return this.outDegreeOf(vertexOrKey) + this.inDegreeOf(vertexOrKey); } /** * The function "inDegreeOf" returns the number of incoming edges for a given vertex. - * @param {VertexKey | V} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `V`. + * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`. * @returns The number of incoming edges of the specified vertex or vertex ID. */ - inDegreeOf(vertexOrKey: VertexKey | V): number { + inDegreeOf(vertexOrKey: VertexKey | VO): number { return this.incomingEdgesOf(vertexOrKey).length; } /** * The function `outDegreeOf` returns the number of outgoing edges from a given vertex. - * @param {VertexKey | V} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `V`. + * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`. * @returns The number of outgoing edges from the specified vertex or vertex ID. */ - outDegreeOf(vertexOrKey: VertexKey | V): number { + outDegreeOf(vertexOrKey: VertexKey | VO): number { return this.outgoingEdgesOf(vertexOrKey).length; } /** * The function "edgesOf" returns an array of both outgoing and incoming edges of a given vertex or vertex ID. - * @param {VertexKey | V} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `V`. + * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`. * @returns The function `edgesOf` returns an array of edges. */ - edgesOf(vertexOrKey: VertexKey | V): E[] { + edgesOf(vertexOrKey: VertexKey | VO): EO[] { return [...this.outgoingEdgesOf(vertexOrKey), ...this.incomingEdgesOf(vertexOrKey)]; } /** * The function "getEdgeSrc" returns the source vertex of an edge, or null if the edge does not exist. - * @param {E} e - The parameter "e" is of type E, which represents an edge in a graph. - * @returns either a vertex object (V) or null. + * @param {EO} e - The parameter "e" is of type EO, which represents an edge in a graph. + * @returns either a vertex object (VO) or null. */ - getEdgeSrc(e: E): V | null { + getEdgeSrc(e: EO): VO | null { return this._getVertex(e.src); } /** * The function "getEdgeDest" returns the destination vertex of an edge. - * @param {E} e - The parameter "e" is of type "E", which represents an edge in a graph. - * @returns either a vertex object of type V or null. + * @param {EO} e - The parameter "e" is of type "EO", which represents an edge in a graph. + * @returns either a vertex object of type VO or null. */ - getEdgeDest(e: E): V | null { + getEdgeDest(e: EO): VO | null { return this._getVertex(e.dest); } /** * The function `getDestinations` returns an array of destination vertices connected to a given vertex. - * @param {V | VertexKey | null} vertex - The `vertex` parameter represents the starting vertex from which we want to - * find the destinations. It can be either a `V` object, a `VertexKey` value, or `null`. - * @returns an array of vertices (V[]). + * @param {VO | VertexKey | null} vertex - The `vertex` parameter represents the starting vertex from which we want to + * find the destinations. It can be either a `VO` object, a `VertexKey` value, or `null`. + * @returns an array of vertices (VO[]). */ - getDestinations(vertex: V | VertexKey | null): V[] { + getDestinations(vertex: VO | VertexKey | null): VO[] { if (vertex === null) { return []; } - const destinations: V[] = []; + const destinations: VO[] = []; const outgoingEdges = this.outgoingEdgesOf(vertex); for (const outEdge of outgoingEdges) { const child = this.getEdgeDest(outEdge); @@ -332,18 +337,18 @@ export class DirectedGraph = DirectedVertex, E ext * specified, the vertices themselves will be used for sorting. If 'key' is specified, the ids of * @returns an array of vertices or vertex IDs in topological order. If there is a cycle in the graph, it returns null. */ - topologicalSort(propertyName?: 'vertex' | 'key'): Array | null { + topologicalSort(propertyName?: 'vertex' | 'key'): Array | null { propertyName = propertyName ?? 'key'; // When judging whether there is a cycle in the undirected graph, all nodes with degree of **<= 1** are enqueued // When judging whether there is a cycle in the directed graph, all nodes with **in degree = 0** are enqueued - const statusMap: Map = new Map(); + const statusMap: Map = new Map(); for (const entry of this.vertices) { statusMap.set(entry[1], 0); } - let sorted: (V | VertexKey)[] = []; + let sorted: (VO | VertexKey)[] = []; let hasCycle = false; - const dfs = (cur: V | VertexKey) => { + const dfs = (cur: VO | VertexKey) => { statusMap.set(cur, 1); const children = this.getDestinations(cur); for (const child of children) { @@ -372,10 +377,10 @@ export class DirectedGraph = DirectedVertex, E ext /** * The `edgeSet` function returns an array of all the edges in the graph. - * @returns The `edgeSet()` method returns an array of edges (`E[]`). + * @returns The `edgeSet()` method returns an array of edges (`EO[]`). */ - edgeSet(): E[] { - let edges: E[] = []; + edgeSet(): EO[] { + let edges: EO[] = []; this._outEdgeMap.forEach(outEdges => { edges = [...edges, ...outEdges]; }); @@ -384,12 +389,12 @@ export class DirectedGraph = DirectedVertex, E ext /** * The function `getNeighbors` returns an array of neighboring vertices of a given vertex or vertex ID in a graph. - * @param {V | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`V`) or a vertex ID + * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID * (`VertexKey`). - * @returns an array of vertices (V[]). + * @returns an array of vertices (VO[]). */ - getNeighbors(vertexOrKey: V | VertexKey): V[] { - const neighbors: V[] = []; + getNeighbors(vertexOrKey: VO | VertexKey): VO[] { + const neighbors: VO[] = []; const vertex = this._getVertex(vertexOrKey); if (vertex) { const outEdges = this.outgoingEdgesOf(vertex); @@ -407,11 +412,11 @@ export class DirectedGraph = DirectedVertex, E ext /** * The function "getEndsOfEdge" returns the source and destination vertices of an edge if it exists in the graph, * otherwise it returns null. - * @param {E} edge - The parameter `edge` is of type `E`, which represents an edge in a graph. - * @returns The function `getEndsOfEdge` returns an array containing two vertices `[V, V]` if the edge exists in the + * @param {EO} edge - The parameter `edge` is of type `EO`, which represents an edge in a graph. + * @returns The function `getEndsOfEdge` returns an array containing two vertices `[VO, VO]` if the edge exists in the * graph. If the edge does not exist, it returns `null`. */ - getEndsOfEdge(edge: E): [V, V] | null { + getEndsOfEdge(edge: EO): [VO, VO] | null { if (!this.hasEdge(edge.src, edge.dest)) { return null; } @@ -426,12 +431,12 @@ export class DirectedGraph = DirectedVertex, E ext /** * The function `_addEdgeOnly` adds an edge to a graph if the source and destination vertices exist. - * @param {E} edge - The parameter `edge` is of type `E`, which represents an edge in a graph. It is the edge that + * @param {EO} edge - The parameter `edge` is of type `EO`, which represents an edge in a graph. It is the edge that * needs to be added to the graph. * @returns a boolean value. It returns true if the edge was successfully added to the graph, and false if either the * source or destination vertex does not exist in the graph. */ - protected _addEdgeOnly(edge: E): boolean { + protected _addEdgeOnly(edge: EO): boolean { if (!(this.hasVertex(edge.src) && this.hasVertex(edge.dest))) { return false; } @@ -460,11 +465,11 @@ export class DirectedGraph = DirectedVertex, E ext } } - protected _setOutEdgeMap(value: Map) { + protected _setOutEdgeMap(value: Map) { this._outEdgeMap = value; } - protected _setInEdgeMap(value: Map) { + protected _setInEdgeMap(value: Map) { this._inEdgeMap = value; } } diff --git a/src/data-structures/graph/map-graph.ts b/src/data-structures/graph/map-graph.ts index 8d7d71e..6be80f6 100644 --- a/src/data-structures/graph/map-graph.ts +++ b/src/data-structures/graph/map-graph.ts @@ -14,7 +14,7 @@ export class MapVertex extends DirectedVertex { * @param {V} [val] - The "val" parameter is an optional value of type V. It is not required to be provided when * creating an instance of the class. */ - constructor(key: VertexKey, lat: number, long: number, val?: V) { + constructor(key: VertexKey, val: V, lat: number, long: number) { super(key, val); this._lat = lat; this._long = long; @@ -41,7 +41,7 @@ export class MapVertex extends DirectedVertex { } } -export class MapEdge extends DirectedEdge { +export class MapEdge extends DirectedEdge { /** * The constructor function initializes a new instance of a class with the given source, destination, weight, and * value. @@ -49,18 +49,20 @@ export class MapEdge extends DirectedEdge { * a graph. * @param {VertexKey} dest - The `dest` parameter is the identifier of the destination vertex for an edge. * @param {number} [weight] - The weight parameter is an optional number that represents the weight of the edge. - * @param {V} [val] - The "val" parameter is an optional parameter of type V. It is used to store additional + * @param {E} [val] - The "val" parameter is an optional parameter of type E. It is used to store additional * information or data associated with the edge. */ - constructor(src: VertexKey, dest: VertexKey, weight?: number, val?: V) { + constructor(src: VertexKey, dest: VertexKey, weight?: number, val?: E) { super(src, dest, weight, val); } } -export class MapGraph = MapVertex, E extends MapEdge = MapEdge> extends DirectedGraph< - V, - E -> { +export class MapGraph< + V = any, + E = any, + VO extends MapVertex = MapVertex, + EO extends MapEdge = MapEdge +> extends DirectedGraph { /** * The constructor function initializes the origin and bottomRight properties of a MapGraphCoordinate object. * @param {MapGraphCoordinate} origin - The `origin` parameter is a `MapGraphCoordinate` object that represents the @@ -101,19 +103,14 @@ export class MapGraph = MapVertex, E extends MapEd * @param {VertexKey} key - The key parameter is the unique identifier for the vertex. It is of type VertexKey, which could * be a string or a number depending on how you define it in your code. * @param [val] - The `val` parameter is an optional value that can be assigned to the `val` property of the vertex. It - * is of type `V['val']`, which means it should be of the same type as the `val` property of the vertex class `V`. + * is of type `V`, which means it should be of the same type as the `val` property of the vertex class `VO`. * @param {number} lat - The `lat` parameter represents the latitude of the vertex. It is a number that specifies the * position of the vertex on the Earth's surface in the north-south direction. * @param {number} long - The `long` parameter represents the longitude coordinate of the vertex. - * @returns The method is returning a new instance of the `MapVertex` class, casted as type `V`. + * @returns The method is returning a new instance of the `MapVertex` class, casted as type `VO`. */ - override createVertex( - key: VertexKey, - lat: number = this.origin[0], - long: number = this.origin[1], - val?: V['val'] - ): V { - return new MapVertex(key, lat, long, val) as V; + override createVertex(key: VertexKey, val?: V, lat: number = this.origin[0], long: number = this.origin[1]): VO { + return new MapVertex(key, val, lat, long) as VO; } /** @@ -126,9 +123,9 @@ export class MapGraph = MapVertex, E extends MapEd * If the weight is not provided, it can be set to a default value or left undefined. * @param [val] - The `val` parameter is an optional value that can be assigned to the edge. It can be of any type, * depending on the specific implementation of the `MapEdge` class. - * @returns a new instance of the `MapEdge` class, cast as type `E`. + * @returns a new instance of the `MapEdge` class, cast as type `EO`. */ - override createEdge(src: VertexKey, dest: VertexKey, weight?: number, val?: E['val']): E { - return new MapEdge(src, dest, weight, val) as E; + override createEdge(src: VertexKey, dest: VertexKey, weight?: number, val?: E): EO { + return new MapEdge(src, dest, weight, val) as EO; } } diff --git a/src/data-structures/graph/undirected-graph.ts b/src/data-structures/graph/undirected-graph.ts index 1380542..7adeb28 100644 --- a/src/data-structures/graph/undirected-graph.ts +++ b/src/data-structures/graph/undirected-graph.ts @@ -23,7 +23,7 @@ export class UndirectedVertex extends AbstractVertex { } } -export class UndirectedEdge extends AbstractEdge { +export class UndirectedEdge extends AbstractEdge { /** * The constructor function creates an instance of a class with two vertex IDs, an optional weight, and an optional * value. @@ -31,10 +31,10 @@ export class UndirectedEdge extends AbstractEdge { * @param {VertexKey} v2 - The parameter `v2` is a `VertexKey`, which represents the identifier of the second vertex in a * graph edge. * @param {number} [weight] - The weight parameter is an optional number that represents the weight of the edge. - * @param {V} [val] - The "val" parameter is an optional parameter of type V. It is used to store a value associated + * @param {E} [val] - The "val" parameter is an optional parameter of type E. It is used to store a value associated * with the edge. */ - constructor(v1: VertexKey, v2: VertexKey, weight?: number, val?: V) { + constructor(v1: VertexKey, v2: VertexKey, weight?: number, val?: E) { super(weight, val); this._vertices = [v1, v2]; } @@ -51,23 +51,25 @@ export class UndirectedEdge extends AbstractEdge { } export class UndirectedGraph< - V extends UndirectedVertex = UndirectedVertex, - E extends UndirectedEdge = UndirectedEdge + V = any, + E = any, + VO extends UndirectedVertex = UndirectedVertex, + EO extends UndirectedEdge = UndirectedEdge > - extends AbstractGraph - implements IGraph + extends AbstractGraph + implements IGraph { /** * The constructor initializes a new Map object to store edges. */ constructor() { super(); - this._edges = new Map(); + this._edges = new Map(); } - protected _edges: Map; + protected _edges: Map; - get edges(): Map { + get edges(): Map { return this._edges; } @@ -78,10 +80,10 @@ export class UndirectedGraph< * @param [val] - The `val` parameter is an optional value that can be assigned to the vertex. If a value is provided, * it will be used as the value of the vertex. If no value is provided, the `key` parameter will be used as the value of * the vertex. - * @returns The method is returning a new instance of the `UndirectedVertex` class, casted as type `V`. + * @returns The method is returning a new instance of the `UndirectedVertex` class, casted as type `VO`. */ - override createVertex(key: VertexKey, val?: V['val']): V { - return new UndirectedVertex(key, val ?? key) as V; + override createVertex(key: VertexKey, val?: VO['val']): VO { + return new UndirectedVertex(key, val ?? key) as VO; } /** @@ -92,26 +94,26 @@ export class UndirectedGraph< * no weight is provided, it defaults to 1. * @param [val] - The `val` parameter is an optional value that can be assigned to the edge. It can be of any type and * is used to store additional information or data associated with the edge. - * @returns a new instance of the `UndirectedEdge` class, which is casted as type `E`. + * @returns a new instance of the `UndirectedEdge` class, which is casted as type `EO`. */ - override createEdge(v1: VertexKey, v2: VertexKey, weight?: number, val?: E['val']): E { - return new UndirectedEdge(v1, v2, weight ?? 1, val) as E; + override createEdge(v1: VertexKey, v2: VertexKey, weight?: number, val?: EO['val']): EO { + return new UndirectedEdge(v1, v2, weight ?? 1, val) as EO; } /** * The function `getEdge` returns the first edge that connects two vertices, or null if no such edge exists. - * @param {V | null | VertexKey} v1 - The parameter `v1` represents a vertex or vertex ID. It can be of type `V` (vertex + * @param {VO | null | VertexKey} v1 - The parameter `v1` represents a vertex or vertex ID. It can be of type `VO` (vertex * object), `null`, or `VertexKey` (a string or number representing the ID of a vertex). - * @param {V | null | VertexKey} v2 - The parameter `v2` represents a vertex or vertex ID. It can be of type `V` (vertex + * @param {VO | null | VertexKey} v2 - The parameter `v2` represents a vertex or vertex ID. It can be of type `VO` (vertex * object), `null`, or `VertexKey` (vertex ID). - * @returns an edge (E) or null. + * @returns an edge (EO) or null. */ - getEdge(v1: V | null | VertexKey, v2: V | null | VertexKey): E | null { - let edges: E[] | undefined = []; + getEdge(v1: VO | null | VertexKey, v2: VO | null | VertexKey): EO | null { + let edges: EO[] | undefined = []; if (v1 !== null && v2 !== null) { - const vertex1: V | null = this._getVertex(v1); - const vertex2: V | null = this._getVertex(v2); + const vertex1: VO | null = this._getVertex(v1); + const vertex2: VO | null = this._getVertex(v2); if (vertex1 && vertex2) { edges = this._edges.get(vertex1)?.filter(e => e.vertices.includes(vertex2.key)); @@ -123,48 +125,48 @@ export class UndirectedGraph< /** * The function removes an edge between two vertices in a graph and returns the removed edge. - * @param {V | VertexKey} v1 - The parameter `v1` represents either a vertex object (`V`) or a vertex ID (`VertexKey`). - * @param {V | VertexKey} v2 - V | VertexKey - This parameter can be either a vertex object (V) or a vertex ID + * @param {VO | VertexKey} v1 - The parameter `v1` represents either a vertex object (`VO`) or a vertex ID (`VertexKey`). + * @param {VO | VertexKey} v2 - VO | VertexKey - This parameter can be either a vertex object (VO) or a vertex ID * (VertexKey). It represents the second vertex of the edge that needs to be removed. - * @returns the removed edge (E) if it exists, or null if either of the vertices (V) does not exist. + * @returns the removed edge (EO) if it exists, or null if either of the vertices (VO) does not exist. */ - deleteEdgeBetween(v1: V | VertexKey, v2: V | VertexKey): E | null { - const vertex1: V | null = this._getVertex(v1); - const vertex2: V | null = this._getVertex(v2); + deleteEdgeBetween(v1: VO | VertexKey, v2: VO | VertexKey): EO | null { + const vertex1: VO | null = this._getVertex(v1); + const vertex2: VO | null = this._getVertex(v2); if (!vertex1 || !vertex2) { return null; } const v1Edges = this._edges.get(vertex1); - let removed: E | null = null; + let removed: EO | null = null; if (v1Edges) { - removed = arrayRemove(v1Edges, (e: E) => e.vertices.includes(vertex2.key))[0] || null; + removed = arrayRemove(v1Edges, (e: EO) => e.vertices.includes(vertex2.key))[0] || null; } const v2Edges = this._edges.get(vertex2); if (v2Edges) { - arrayRemove(v2Edges, (e: E) => e.vertices.includes(vertex1.key)); + arrayRemove(v2Edges, (e: EO) => e.vertices.includes(vertex1.key)); } return removed; } /** * The deleteEdge function removes an edge between two vertices in a graph. - * @param {E} edge - The parameter "edge" is of type E, which represents an edge in a graph. - * @returns The method is returning either the removed edge (of type E) or null if the edge was not found. + * @param {EO} edge - The parameter "edge" is of type EO, which represents an edge in a graph. + * @returns The method is returning either the removed edge (of type EO) or null if the edge was not found. */ - deleteEdge(edge: E): E | null { + deleteEdge(edge: EO): EO | null { return this.deleteEdgeBetween(edge.vertices[0], edge.vertices[1]); } /** * The function `degreeOf` returns the degree of a vertex in a graph, which is the number of edges connected to that * vertex. - * @param {VertexKey | V} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `V`. + * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`. * @returns The function `degreeOf` returns the degree of a vertex in a graph. The degree of a vertex is the number of * edges connected to that vertex. */ - degreeOf(vertexOrKey: VertexKey | V): number { + degreeOf(vertexOrKey: VertexKey | VO): number { const vertex = this._getVertex(vertexOrKey); if (vertex) { return this._edges.get(vertex)?.length || 0; @@ -175,11 +177,11 @@ export class UndirectedGraph< /** * The function returns the edges of a given vertex or vertex ID. - * @param {VertexKey | V} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `V`. A `VertexKey` is a - * unique identifier for a vertex in a graph, while `V` represents the type of the vertex. + * @param {VertexKey | VO} vertexOrKey - The parameter `vertexOrKey` can be either a `VertexKey` or a `VO`. A `VertexKey` is a + * unique identifier for a vertex in a graph, while `VO` represents the type of the vertex. * @returns an array of edges. */ - edgesOf(vertexOrKey: VertexKey | V): E[] { + edgesOf(vertexOrKey: VertexKey | VO): EO[] { const vertex = this._getVertex(vertexOrKey); if (vertex) { return this._edges.get(vertex) || []; @@ -190,10 +192,10 @@ export class UndirectedGraph< /** * The function "edgeSet" returns an array of unique edges from a set of edges. - * @returns The method `edgeSet()` returns an array of type `E[]`. + * @returns The method `edgeSet()` returns an array of type `EO[]`. */ - edgeSet(): E[] { - const edgeSet: Set = new Set(); + edgeSet(): EO[] { + const edgeSet: Set = new Set(); this._edges.forEach(edges => { edges.forEach(edge => { edgeSet.add(edge); @@ -204,12 +206,12 @@ export class UndirectedGraph< /** * The function "getNeighbors" returns an array of neighboring vertices for a given vertex or vertex ID. - * @param {V | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`V`) or a vertex ID + * @param {VO | VertexKey} vertexOrKey - The parameter `vertexOrKey` can be either a vertex object (`VO`) or a vertex ID * (`VertexKey`). - * @returns an array of vertices (V[]). + * @returns an array of vertices (VO[]). */ - getNeighbors(vertexOrKey: V | VertexKey): V[] { - const neighbors: V[] = []; + getNeighbors(vertexOrKey: VO | VertexKey): VO[] { + const neighbors: VO[] = []; const vertex = this._getVertex(vertexOrKey); if (vertex) { const neighborEdges = this.edgesOf(vertex); @@ -226,11 +228,11 @@ export class UndirectedGraph< /** * The function "getEndsOfEdge" returns the vertices at the ends of an edge if the edge exists in the graph, otherwise * it returns null. - * @param {E} edge - The parameter "edge" is of type E, which represents an edge in a graph. - * @returns The function `getEndsOfEdge` returns an array containing two vertices `[V, V]` if the edge exists in the + * @param {EO} edge - The parameter "edge" is of type EO, which represents an edge in a graph. + * @returns The function `getEndsOfEdge` returns an array containing two vertices `[VO, VO]` if the edge exists in the * graph. If the edge does not exist, it returns `null`. */ - getEndsOfEdge(edge: E): [V, V] | null { + getEndsOfEdge(edge: EO): [VO, VO] | null { if (!this.hasEdge(edge.vertices[0], edge.vertices[1])) { return null; } @@ -245,10 +247,10 @@ export class UndirectedGraph< /** * The function adds an edge to the graph by updating the adjacency list with the vertices of the edge. - * @param {E} edge - The parameter "edge" is of type E, which represents an edge in a graph. + * @param {EO} edge - The parameter "edge" is of type EO, which represents an edge in a graph. * @returns a boolean value. */ - protected _addEdgeOnly(edge: E): boolean { + protected _addEdgeOnly(edge: EO): boolean { for (const end of edge.vertices) { const endVertex = this._getVertex(end); if (endVertex === null) return false; @@ -266,9 +268,9 @@ export class UndirectedGraph< /** * The function sets the edges of a graph. - * @param v - A map where the keys are of type V and the values are arrays of type E. + * @param v - A map where the keys are of type VO and the values are arrays of type EO. */ - protected _setEdges(v: Map) { + protected _setEdges(v: Map) { this._edges = v; } } diff --git a/src/data-structures/queue/queue.ts b/src/data-structures/queue/queue.ts index 0f9e1a2..abc7ad1 100644 --- a/src/data-structures/queue/queue.ts +++ b/src/data-structures/queue/queue.ts @@ -5,7 +5,7 @@ */ import {SinglyLinkedList} from '../linked-list'; -export class LinkedListQueue extends SinglyLinkedList { +export class SkipQueue extends SinglyLinkedList { /** * The enqueue function adds a value to the end of an array. * @param {E} value - The value parameter represents the value that you want to add to the queue. diff --git a/src/interfaces/graph.ts b/src/interfaces/graph.ts index dd65e90..eae6ae9 100644 --- a/src/interfaces/graph.ts +++ b/src/interfaces/graph.ts @@ -1,7 +1,7 @@ import {VertexKey} from '../types'; -export interface IGraph { - createVertex(key: VertexKey, val?: V): V; +export interface IGraph { + createVertex(key: VertexKey, val?: V): VO; - createEdge(srcOrV1: VertexKey | string, destOrV2: VertexKey | string, weight?: number, val?: E): E; + createEdge(srcOrV1: VertexKey | string, destOrV2: VertexKey | string, weight?: number, val?: E): EO; } diff --git a/test/unit/data-structures/graph/directed-graph.test.ts b/test/unit/data-structures/graph/directed-graph.test.ts index 91cb054..fdb90f2 100644 --- a/test/unit/data-structures/graph/directed-graph.test.ts +++ b/test/unit/data-structures/graph/directed-graph.test.ts @@ -92,52 +92,57 @@ describe('DirectedGraph Operation Test', () => { }); }); -class MyVertex extends DirectedVertex { +class MyVertex extends DirectedVertex { constructor(key: VertexKey, val?: V) { super(key, val); this._data = val; } - private _data: string | undefined; + private _data: V | undefined; - get data(): string | undefined { + get data(): V | undefined { return this._data; } - set data(value: string | undefined) { + set data(value: V | undefined) { this._data = value; } } -class MyEdge extends DirectedEdge { +class MyEdge extends DirectedEdge { constructor(v1: VertexKey, v2: VertexKey, weight?: number, val?: E) { super(v1, v2, weight, val); this._data = val; } - private _data: string | undefined; + private _data: E | undefined; - get data(): string | undefined { + get data(): E | undefined { return this._data; } - set data(value: string | undefined) { + set data(value: E | undefined) { this._data = value; } } -class MyDirectedGraph, E extends MyEdge> extends DirectedGraph { - createVertex(key: VertexKey, val: V['val']): V { - return new MyVertex(key, val) as V; +class MyDirectedGraph< + V = any, + E = any, + VO extends MyVertex = MyVertex, + EO extends MyEdge = MyEdge +> extends DirectedGraph { + createVertex(key: VertexKey, val: V): VO { + return new MyVertex(key, val) as VO; } - createEdge(src: VertexKey, dest: VertexKey, weight?: number, val?: E['val']): E { - return new MyEdge(src, dest, weight ?? 1, val) as E; + createEdge(src: VertexKey, dest: VertexKey, weight?: number, val?: E): EO { + return new MyEdge(src, dest, weight ?? 1, val) as EO; } } describe('Inherit from DirectedGraph and perform operations', () => { - let myGraph = new MyDirectedGraph, MyEdge>(); + let myGraph = new MyDirectedGraph(); beforeEach(() => { myGraph = new MyDirectedGraph(); }); @@ -234,7 +239,7 @@ describe('Inherit from DirectedGraph and perform operations', () => { }); describe('Inherit from DirectedGraph and perform operations test2.', () => { - const myGraph = new MyDirectedGraph, MyEdge>(); + const myGraph = new MyDirectedGraph(); it('should test graph operations', () => { const vertex1 = new MyVertex(1, 'data1'); diff --git a/test/unit/data-structures/graph/map-graph.test.ts b/test/unit/data-structures/graph/map-graph.test.ts index 0c88ddd..94555c7 100644 --- a/test/unit/data-structures/graph/map-graph.test.ts +++ b/test/unit/data-structures/graph/map-graph.test.ts @@ -4,17 +4,17 @@ describe('MapGraph Operation Test', () => { it('dijkstra shortest path', () => { const mapGraph = new MapGraph([5.500338, 100.173665]); - mapGraph.addVertex(new MapVertex('Surin', 5.466724, 100.274805)); - mapGraph.addVertex(new MapVertex('Batu Feringgi Beach', 5.475141, 100.27667)); - mapGraph.addVertex(new MapVertex('Lotus', 5.459044, 100.308767)); - mapGraph.addVertex(new MapVertex('The Breeza', 5.454197, 100.307859)); - mapGraph.addVertex(new MapVertex('Hard Rock Hotel', 5.46785, 100.241876)); - mapGraph.addVertex(new MapVertex('Mira', 5.456749, 100.28665)); - mapGraph.addVertex(new MapVertex('Penang Bible Church', 5.428683, 100.314825)); - mapGraph.addVertex(new MapVertex('Queensbay', 5.33276, 100.306651)); - mapGraph.addVertex(new MapVertex('Saanen Goat Farm', 5.405738, 100.207699)); - mapGraph.addVertex(new MapVertex('Trinity Auto', 5.401126, 100.303739)); - mapGraph.addVertex(new MapVertex('Penang Airport', 5.293185, 100.265772)); + mapGraph.addVertex(new MapVertex('Surin', '', 5.466724, 100.274805)); + mapGraph.addVertex(new MapVertex('Batu Feringgi Beach', '', 5.475141, 100.27667)); + mapGraph.addVertex(new MapVertex('Lotus', '', 5.459044, 100.308767)); + mapGraph.addVertex(new MapVertex('The Breeza', '', 5.454197, 100.307859)); + mapGraph.addVertex(new MapVertex('Hard Rock Hotel', '', 5.46785, 100.241876)); + mapGraph.addVertex(new MapVertex('Mira', '', 5.456749, 100.28665)); + mapGraph.addVertex(new MapVertex('Penang Bible Church', '', 5.428683, 100.314825)); + mapGraph.addVertex(new MapVertex('Queensbay', '', 5.33276, 100.306651)); + mapGraph.addVertex(new MapVertex('Saanen Goat Farm', '', 5.405738, 100.207699)); + mapGraph.addVertex(new MapVertex('Trinity Auto', '', 5.401126, 100.303739)); + mapGraph.addVertex(new MapVertex('Penang Airport', '', 5.293185, 100.265772)); mapGraph.addEdge('Surin', 'Lotus', 4.7); mapGraph.addEdge('Lotus', 'The Breeza', 1); mapGraph.addEdge('Batu Feringgi Beach', 'Hard Rock Hotel', 5.2); @@ -45,17 +45,17 @@ describe('MapGraph Operation Test', () => { }); describe('MapGraph', () => { - let mapGraph: MapGraph; + let mapGraph: MapGraph; beforeEach(() => { // Create a new MapGraph instance before each test - mapGraph = new MapGraph([0, 0], [100, 100]); + mapGraph = new MapGraph([0, 0], [100, 100]); }); // Test adding vertices to the graph it('should add vertices to the graph', () => { - const locationA = new MapVertex('A', 10, 20, 'Location A'); - const locationB = new MapVertex('B', 30, 40, 'Location B'); + const locationA = new MapVertex('A', 'Location A', 10, 20); + const locationB = new MapVertex('B', 'Location B', 30, 40); mapGraph.addVertex(locationA); mapGraph.addVertex(locationB); @@ -66,8 +66,8 @@ describe('MapGraph', () => { // Test adding edges to the graph it('should add edges to the graph', () => { - const locationA = new MapVertex('A', 10, 20, 'Location A'); - const locationB = new MapVertex('B', 30, 40, 'Location B'); + const locationA = new MapVertex('A', 'Location A', 10, 20); + const locationB = new MapVertex('B', 'Location B', 30, 40); const edgeAB = new MapEdge('A', 'B', 50, 'Edge from A to B'); mapGraph.addVertex(locationA); @@ -79,12 +79,12 @@ describe('MapGraph', () => { // Test getting neighbors of a vertex it('should return the neighbors of a vertex', () => { - const locationA = new MapVertex('A', 10, 20, 'Location A'); + const locationA = new MapVertex('A', 'Location A', 10, 20); locationA.lat = locationA.lat; locationA.long = locationA.long; - const locationB = mapGraph.createVertex('B', 30, 40, 'Location B'); + const locationB = mapGraph.createVertex('B', 'Location B', 30, 40); - const locationC = new MapVertex('C', 50, 60, 'Location C'); + const locationC = new MapVertex('C', 'Location C', 50, 60); const edgeAB = new MapEdge('A', 'B', 50, 'Edge from A to B'); const edgeBC = new MapEdge('B', 'C', 60, 'Edge from B to C'); @@ -106,9 +106,9 @@ describe('MapGraph', () => { // Test finding the shortest path between locations it('should find the shortest path between two locations', () => { - const locationA = new MapVertex('A', 10, 20, 'Location A'); - const locationB = new MapVertex('B', 30, 40, 'Location B'); - const locationC = new MapVertex('C', 50, 60, 'Location C'); + const locationA = new MapVertex('A', 'Location A', 10, 20); + const locationB = new MapVertex('B', 'Location B', 30, 40); + const locationC = new MapVertex('C', 'Location C', 50, 60); const edgeAB = new MapEdge('A', 'B', 50, 'Edge from A to B'); const edgeBC = new MapEdge('B', 'C', 60, 'Edge from B to C'); diff --git a/test/unit/data-structures/graph/undirected-graph.test.ts b/test/unit/data-structures/graph/undirected-graph.test.ts index c331fd6..622f29f 100644 --- a/test/unit/data-structures/graph/undirected-graph.test.ts +++ b/test/unit/data-structures/graph/undirected-graph.test.ts @@ -59,11 +59,11 @@ describe('UndirectedGraph Operation Test', () => { }); describe('UndirectedGraph', () => { - let undirectedGraph: UndirectedGraph, UndirectedEdge>; + let undirectedGraph: UndirectedGraph; beforeEach(() => { // Create a new UndirectedGraph instance before each test - undirectedGraph = new UndirectedGraph, UndirectedEdge>(); + undirectedGraph = new UndirectedGraph(); }); // Test adding vertices to the graph diff --git a/test/unit/data-structures/queue/queue.test.ts b/test/unit/data-structures/queue/queue.test.ts index 9e2a263..eb062f6 100644 --- a/test/unit/data-structures/queue/queue.test.ts +++ b/test/unit/data-structures/queue/queue.test.ts @@ -1,4 +1,4 @@ -import {LinkedListQueue, Queue} from '../../../../src'; +import {SkipQueue, Queue} from '../../../../src'; import {bigO, magnitude} from '../../../utils'; import {isDebugTest} from '../../../config'; @@ -168,11 +168,11 @@ describe('Queue', () => { expect(values).toEqual([1, 2, 3]); }); }); -describe('LinkedListQueue', () => { - let queue: LinkedListQueue; +describe('SkipQueue', () => { + let queue: SkipQueue; beforeEach(() => { - queue = new LinkedListQueue(); + queue = new SkipQueue(); }); it('should enqueue elements to the end of the queue', () => { @@ -197,7 +197,7 @@ describe('LinkedListQueue', () => { expect(queue.peek()).toBe('A'); }); - // Add more test cases for other methods of LinkedListQueue. + // Add more test cases for other methods of SkipQueue. }); describe('Queue Performance Test', () => { @@ -228,16 +228,16 @@ describe('Queue Performance Test', () => { expect(performance.now() - startTime2).toBeLessThan(bigO.CUBED * 100); }); - it('should numeric LinkedListQueue be efficient', function () { + it('should numeric SkipQueue be efficient', function () { const startTime = performance.now(); - const queue = new LinkedListQueue(); + const queue = new SkipQueue(); for (let i = 0; i < dataSize; i++) { queue.enqueue(i); } for (let i = 0; i < dataSize; i++) { queue.dequeue(); } - console.log(`LinkedListQueue Performance Test: ${performance.now() - startTime} ms`); + console.log(`SkipQueue Performance Test: ${performance.now() - startTime} ms`); expect(performance.now() - startTime).toBeLessThan(bigO.LINEAR * 100); }); });