Reputation: 3761
I have the following array:
steps=[
{from:1, to:8},
{from:1, to:2},
{from:2, to:7},
{from:7, to:9},
{from:8, to:9}
];
this array is describe where does it has connection between two point. For example from 1 to 7 there is a way 1->2->7.
In JavaScript how can I generate the for example the shortest way from 1 to 9?
Updated
function calc_route(start, end, data)
{
console.log(start+", "+end);
console.log(data);
for(var i=0; i<data.length; i++)
{
if(data[i].topoint == end && data[i].frompoint == start)
{
console.log("Return");
console.log(data[i]);
return data[i];
}
else
{
if(data[i].frompoint == start)
{
calcfor = data.splice(i, 1);
calc_route(calcfor[0].topoint, end, data);
}
}
}
}
This is what I done until now, my question is how can I save the path?
Upvotes: 0
Views: 1785
Reputation: 3761
Here is the solution:
function calc_route(start, end, data, mypath, solution)
{
mypath.push(parseInt(start));
for(var i=0; i<data.length; i++)
{
if(data[i].topoint == end && data[i].frompoint == start)
{
mypath.push(end);
solution.push(mypath);
return end;
}
else
{
if(data[i].frompoint == start)
{
calcfor = data.slice(0);
calcfor.splice(i,1);
calc_route(data[i].topoint, end, calcfor, mypath.slice(0), solution);
}
}
}
}
Upvotes: 0
Reputation: 234795
The standard way to find lowest-cost paths is either the A* algorithm (which can use heuristic knowledge) or Dijkstra's Algorithm (which cannot). Both of these links have pseudocode that can be readily converted to Javascript.
Upvotes: 7