JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div id="values">Tristram to AlphaCentauri = 34
Tristram to Snowdin = 100
Tristram to Tambi = 63
Tristram to Faerun = 108
Tristram to Norrath = 111
Tristram to Straylight = 89
Tristram to Arbre = 132
AlphaCentauri to Snowdin = 4
AlphaCentauri to Tambi = 79
AlphaCentauri to Faerun = 44
AlphaCentauri to Norrath = 147
AlphaCentauri to Straylight = 133
AlphaCentauri to Arbre = 74
Snowdin to Tambi = 105
Snowdin to Faerun = 95
Snowdin to Norrath = 48
Snowdin to Straylight = 88
Snowdin to Arbre = 7
Tambi to Faerun = 68
Tambi to Norrath = 134
Tambi to Straylight = 107
Tambi to Arbre = 40
Faerun to Norrath = 11
Faerun to Straylight = 66
Faerun to Arbre = 144
Norrath to Straylight = 115
Norrath to Arbre = 135
Straylight to Arbre = 127</div>
<div id = "results"></div>
</body>
JavaScript
/**
* Created by jbush_000 on 12/9/2015.
*/
var routes = [];
var routesPossible = [];
var usedRoutes = [];
var cities = [];
hide(document.getElementById('values'));
console.log("here");
var values = document.getElementById('values').innerHTML.split(/\r\n|\r|\n/g);
values.forEach(function(direction) {
var nodes = direction.trim().split(" ");
if (cities.indexOf(nodes[0]) == -1) {
cities.push(nodes[0])
}
if (cities.indexOf(nodes[2]) == -1) {
cities.push(nodes[2])
}
routes.push({
cityA: nodes[0],
cityB: nodes[2],
distance: nodes[4]
});
routes.push({
cityA: nodes[2],
cityB: nodes[0],
distance: nodes[4]
});
});
routesPossible = permute(cities);
getDistances();
var shortestRoute = 0;
var longestRoute = 0;
routesPossible.forEach(function(c) {
if (shortestRoute == 0 || c.distance < shortestRoute) {
shortestRoute = c.distance;
}
if (longestRoute == 0 || c.distance > longestRoute) {
longestRoute = c.distance;
}
});
document.getElementById('results').innerHTML = "Part 1: " + shortestRoute +
"<br/>Part 2: " + longestRoute;
function getDistances() {
var distance = 0;
routesPossible.forEach(function(c) {
distance = 0;
for (count = 0; count < c.length - 1; count++) {
var routeNeeded = routes.filter(function(route) {
return route.cityA == c[count] && route.cityB == c[count + 1]
})[0];
distance += parseInt(routeNeeded.distance);
}
c.distance = distance;
});
}
function permute(input) {
var i, ch;
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedRoutes.push(ch);
if (input.length == 0) {
routesPossible.push(usedRoutes.slice());
}
permute(input);
input.splice(i, 0, ch);
usedRoutes.pop();
}
return routesPossible
}
function hide (elements) {
elements = elements.length ? elements : [elements];
for (var index = 0; index < elements.length; index++) {
elements[index].style.display = 'none';
}
}