Skip to content

Instantly share code, notes, and snippets.

@kana-sama
Created June 13, 2016 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kana-sama/664273aa2fb5977af7bffbff48a10a86 to your computer and use it in GitHub Desktop.
Save kana-sama/664273aa2fb5977af7bffbff48a10a86 to your computer and use it in GitHub Desktop.
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