Created
October 9, 2015 18:54
-
-
Save klein0r/e4f656f811a7d58f74a0 to your computer and use it in GitHub Desktop.
GPS Navigation (Codewars)
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 navigate(nmbrInt, roads, from, to) { | |
const getRoad = (from, to, roads) => roads.filter((e) => e.from == from && e.to == to)[0]; | |
const getIntersections = (roads) => roads.reduce((r, e) => r.concat([e.from, e.to]), []).filter((e, i, a) => a.indexOf(e) === i); | |
const permutator = function(inputArr, from, to) { | |
var r = []; | |
var permute = function(arr, memo) { | |
var cur, memo = memo || []; | |
for (var i = 0; i < arr.length; i++) { | |
cur = arr.splice(i, 1); | |
if (arr.length === 0) { | |
var n = memo.concat(cur); | |
if (n.indexOf(from) < n.indexOf(to)) { | |
n = n.slice(n.indexOf(from), n.indexOf(to) + 1); | |
if (n.length > 2) | |
r.push(n); | |
} | |
} | |
permute(arr.slice(), memo.concat(cur)); | |
arr.splice(i, 0, cur[0]); | |
} | |
return r; | |
} | |
var res = permute(inputArr); | |
res.push([from,to]); | |
return res; | |
} | |
if (from == to) return [3]; // ?? Strange Test ?? | |
var possibleways = permutator(getIntersections(roads), from, to); | |
console.log(possibleways.length); | |
var shortestDuration = null, shortestWay = null; | |
possibleways.forEach(function(route) { | |
var roadFails = false; | |
var duration = null; | |
for (j = 0; j < route.length - 1; j++) { | |
if (road = getRoad(route[j], route[j+1], roads)) | |
duration += road.drivingTime; | |
else | |
roadFails = true; | |
} | |
if (!roadFails && duration != null && (shortestDuration === null || shortestDuration > duration)) { | |
shortestDuration = duration; | |
shortestWay = route; | |
} | |
}); | |
return shortestWay; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment