-
-
Save kana-sama/664273aa2fb5977af7bffbff48a10a86 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
class Intersection { | |
constructor(id) { | |
this.id = id | |
this.roads = [] | |
this.timeBeforeArrival = Infinity | |
} | |
addRoad({ destination, drivingTime }) { | |
this.roads.push({ destination, drivingTime }) | |
} | |
startDriving(newTimeBeforeArrival = 0) { | |
this.timeBeforeArrival = newTimeBeforeArrival | |
for (const { destination, drivingTime } of this.roads) { | |
const destinationTimeBeforeArrival = this.timeBeforeArrival + drivingTime | |
if (destination.timeBeforeArrival > destinationTimeBeforeArrival) { | |
destination.startDriving(destinationTimeBeforeArrival) | |
} | |
} | |
} | |
getPathTo(start) { | |
if (this === start) { | |
return [this.id] | |
} | |
let closestIntersection | |
for (const { destination, drivingTime } of this.roads) { | |
if (destination.timeBeforeArrival + drivingTime === this.timeBeforeArrival) { | |
closestIntersection = destination | |
break | |
} | |
} | |
return [...closestIntersection.getPathTo(start), this.id] | |
} | |
} | |
function navigate(numberOfIntersections, roads, startID, finishID) { | |
const intersections = Array.from( | |
new Array(numberOfIntersections), | |
(_, id) => new Intersection(id) | |
) | |
const start = intersections[startID] | |
const finish = intersections[finishID] | |
for (const { from, to, drivingTime } of roads) { | |
intersections[from].addRoad({ destination: intersections[ to ], drivingTime }) | |
intersections[ to ].addRoad({ destination: intersections[from], drivingTime }) | |
} | |
start.startDriving() | |
if (finish.timeBeforeArrival === Infinity) { | |
return null | |
} else { | |
return finish.getPathTo(start) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment