Skip to content

Commit c8c56e7

Browse files
authored
Ravann weightfunction (#1)
Created weightfunction to calculate weights of the path instead of hardcoded value ...
1 parent e1b0e1e commit c8c56e7

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

src/algorithms/shortestPath/getPath.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@ import type { TraversingTracks } from './types.js';
33

44
import { Graph } from '../../Graph.js';
55

6+
export function addWeightFunction(edgeWeight: number, currentPathWeight: number | undefined, hop: number): number {
7+
if (currentPathWeight === undefined) {
8+
return edgeWeight;
9+
}
10+
return edgeWeight + currentPathWeight;
11+
}
12+
613
/**
714
* Assembles the shortest path by traversing the
815
* predecessor subgraph from destination to source.
@@ -12,22 +19,25 @@ export function getPath<Node, LinkProps>(
1219
tracks: TraversingTracks<NoInfer<Node>>,
1320
source: NoInfer<Node>,
1421
destination: NoInfer<Node>,
22+
weightFunction: (edgeWeight: number, currentPathWeight: number, hop: number) => number = addWeightFunction
1523
): {
1624
nodes: [Node, Node, ...Node[]];
1725
weight: number;
1826
} {
1927
const { p } = tracks;
2028
const nodeList: Node[] & { weight?: EdgeWeight } = [];
2129

22-
let totalWeight = 0;
30+
let totalWeight = undefined as unknown as EdgeWeight;
2331
let node = destination;
2432

33+
let hop = 1;
2534
while (p.has(node)) {
2635
const currentNode = p.get(node)!;
2736

2837
nodeList.push(node);
29-
totalWeight += graph.getEdgeWeight(currentNode, node);
38+
totalWeight = weightFunction(graph.getEdgeWeight(currentNode, node), totalWeight, hop);
3039
node = currentNode;
40+
hop++;
3141
}
3242

3343
if (node !== source) {

src/algorithms/shortestPath/shortestPath.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Graph } from '../../Graph.js';
22
import { NoInfer } from '../../types.js';
33
import { dijkstra } from './dijkstra.js';
4-
import { getPath } from './getPath.js';
4+
import { getPath, addWeightFunction } from './getPath.js';
55
import { TraversingTracks } from './types.js';
66

77
/**
@@ -13,6 +13,7 @@ export function shortestPath<Node, LinkProps>(
1313
graph: Graph<Node, LinkProps>,
1414
source: NoInfer<Node>,
1515
destination: NoInfer<Node>,
16+
weightFunction: (edgeWeight: number, currentPathWeight: number, hop: number) => number = addWeightFunction
1617
): {
1718
nodes: [Node, Node, ...Node[]];
1819
weight: number;
@@ -25,5 +26,5 @@ export function shortestPath<Node, LinkProps>(
2526

2627
dijkstra(graph, tracks, source, destination);
2728

28-
return getPath(graph, tracks, source, destination);
29+
return getPath(graph, tracks, source, destination, weightFunction);
2930
}

0 commit comments

Comments
 (0)