Created
December 23, 2015 18:31
-
-
Save danared/52504eb87d80bf30c1ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function visit ( path ) { | |
// get last city visited | |
var city = path.visited[ path.visited.length - 1 ]; | |
var paths = []; | |
db.edges.find( { from: city } ).forEach ( | |
function( edge ) { | |
// avoid cities I've already visited | |
if ( path.visited.indexOf( edge.dest ) == -1 ) { | |
// branch out a new path | |
var newPath = path.clone(); | |
//print( "Adding the next edge "+edge.dest ); | |
newPath.visited.push( edge.dest ); | |
newPath.distance += edge.dist; | |
//recurse | |
paths.push( visit ( newPath ) ); | |
} | |
} | |
); | |
if( paths.length == 0 ) { | |
// if no new paths the tour is complete. Now go home! | |
var lastEdge = db.edges.findOne( | |
{ from: path.visited[ path.visited.length -1 ], | |
dest: path.visited[0] | |
} | |
); | |
path.visited.push( path.visited[0] ); | |
path.distance += lastEdge.dist; | |
print( "Path complete "+path.visited ); | |
paths.push( path ); | |
} | |
paths.sort( compare ); | |
return paths[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment