Click here to Skip to main content
15,887,262 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
Hello, I’m having trouble getting this exercise right (totally stuck at this point):

Complete the missing if-statement body to handle any time a shorter distance from the vertex to the neighbor is discovered:

Consider how the distances and previous objects should be updated to account for the new shorter path.
Use the .add() method to add elements into the queue so you can evaluate the vertices with the shortest distances.

This is my solution:

JavaScript
const PriorityQueue = require(‘./PriorityQueue.js’);
const testGraph = require(‘./testGraph.js’);

const dijkstras = (graph, startingVertex) => {
const distances = {};
const previous = {};
const queue = new PriorityQueue();

queue.add({ vertex: startingVertex, priority: 0 });

graph.vertices.forEach((vertex) => {
distances[vertex.data] = Infinity;
previous[vertex.data] = null;
});

distances[startingVertex.data] = 0;

while (!queue.isEmpty()) {
const { vertex } = queue.popMin();

  vertex.edges.forEach((edge) => {
  	const alternate = edge.weight + distances[vertex.data];
  	const neighborValue = edge.end.data;

  	// THIS IS THE IF STATEMENT:
  	if (alternate < distances[neighborValue]) {
  		distances[neighborValue] = alternate;
  		previous[neighborValue] = vertex.data;

  		queue.add({ vertex: edge.end, priority: alternate });
  	}
  })
}

return { distances, previous };
};

const results = dijkstras(testGraph, testGraph.vertices[0]);
console.log(results);

module.exports = dijkstras;

I keep getting this error:
Make sure to pass in an object with a vertex and priority property to .add()

What I have tried:

This is the if statement I've tried. What am I missing?

if (alternate < distances[neighborValue]) {
  		distances[neighborValue] = alternate;
  		previous[neighborValue] = vertex.data;

  		queue.add({ vertex: edge.end, priority: alternate });
  	}
Posted
Updated 1-Aug-23 7:10am
v3
Comments
Dave Kreskowiak 1-Aug-23 13:16pm    
No, you're not deleting the question. The answer on it wouldn't make sense.

1 solution

If I was you, I would do a quick google search as there are many tutorials with code: javascript dijkstra algorithm - Google Search[^].

Here is the first search result: Dijkstra's algorithm in Javascript[^]. If you do not like that one, there are many more in the search results to choose from.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900