diff --git a/09_dijkstras_algorithm/ts/dijkstras_algorithm.ts b/09_dijkstras_algorithm/ts/dijkstras_algorithm.ts new file mode 100644 index 0000000..67ed318 --- /dev/null +++ b/09_dijkstras_algorithm/ts/dijkstras_algorithm.ts @@ -0,0 +1,59 @@ +import { Graph, GraphIterable } from "./iterable_graph"; + +const dijkstraGraph: Graph> = { + start: { a: 6, b: 2 }, + a: { fin: 1 }, + b: { a: 3, fin: 5 }, + fin: {}, +}; + +const costs: Graph = { + a: 6, + b: 2, + fin: Infinity, +}; + +const parents: Graph = { + a: "start", + b: "start", + fin: null, +}; + +let processed: string[] = []; + +const findLowestCostNode = (costs: Graph): string | null => { + let lowestCost = Infinity; + let lowestCostNode: string | null = null; + + const iterableGraph = new GraphIterable(costs); + + for (const node of iterableGraph) { + const cost = costs[node]; + if (cost < lowestCost && !processed.includes(node)) { + lowestCost = cost; + lowestCostNode = node; + } + } + return lowestCostNode; +}; + +let node = findLowestCostNode(costs); + +while (node !== null) { + const cost = costs[node]; + + const neighbors = dijkstraGraph[node]; + Object.keys(neighbors).forEach((n: string) => { + const newCost = cost + neighbors[n]; + if (costs[n] > newCost) { + costs[n] = newCost; + parents[n] = node; + } + }); + + processed.push(node); + node = findLowestCostNode(costs); +} + +console.log("Cost from the start to each node:"); +console.log(costs); // { a: 5, b: 2, fin: 6 } diff --git a/09_dijkstras_algorithm/ts/iterable_graph.ts b/09_dijkstras_algorithm/ts/iterable_graph.ts new file mode 100644 index 0000000..7ba10b4 --- /dev/null +++ b/09_dijkstras_algorithm/ts/iterable_graph.ts @@ -0,0 +1,26 @@ +export interface Graph { + [key: string]: T; +} + +export class GraphIterable implements Iterable { + private graph: Graph; + + constructor(graph: Graph) { + this.graph = graph; + } + + [Symbol.iterator](): Iterator { + const keys = Object.keys(this.graph); + let index = 0; + + return { + next: (): IteratorResult => { + if (index < keys.length) { + return { value: keys[index++], done: false }; + } else { + return { value: undefined, done: true }; + } + }, + }; + } +}