Skip to content

Instantly share code, notes, and snippets.

@RShergold
Created December 10, 2015 18:01
Show Gist options
  • Save RShergold/bcd513ce24ce94257665 to your computer and use it in GitHub Desktop.
Save RShergold/bcd513ce24ce94257665 to your computer and use it in GitHub Desktop.
adventofcode day 9
var distances = `London to Dublin = 464
London to Belfast = 518
Dublin to Belfast = 141`.split("\n");
var cities = {};
var shortest = {distance:null, route:null};
//Turn the inputs into objects
for (var i=0; i<distances.length; i++) {
var distance = distances[i];
var componenets = distance.match(/([a-zA-Z]+) to ([a-zA-Z]+) = (\d+)/);
distance = parseInt(componenets[3]);
add_place(componenets[1], componenets[2], distance );
add_place(componenets[2], componenets[1], distance );
}
function add_place(place_a, place_b, distance) {
if (!(place_a in cities)) cities[place_a] = {};
cities[place_a][place_b] = distance;
}
// visit each city recursively
function visit(visiting_city, already_visited, distance_traveled) {
already_visited.push(visiting_city);
var at_end_of_tree = true;
for (var next_city in cities[visiting_city]) {
if (already_visited.indexOf(next_city) == -1 ) {
distance = cities[visiting_city][next_city];
visit(next_city, already_visited.slice(), distance_traveled + distance);
at_end_of_tree = false;
}
}
if (at_end_of_tree) {
if (shortest.distance == null | distance_traveled < shortest.distance) {
shortest.distance = distance_traveled;
shortest.route = already_visited.join(' -> ');
}
}
}
//begin by visiting each city
for (var starting_city in cities) {
visit(starting_city, [], 0);
}
console.log(shortest);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment