Last active
November 5, 2018 22:05
-
-
Save novakov-alexey-zz/1a4a742c7693a3ef9c7429f295dd2cc3 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
/** | |
* | |
* @param edgeTo a sequence which represents the last edge | |
* on the shortest path from 'sourceV' to vertex i. | |
* None means there is no path to vertex i | |
* @param distTo a sequence of distances from source vertex to a specific i vertex | |
*/ | |
class ShortestPathCalc(edgeTo: Seq[Option[DirectedEdge]], distTo: Seq[Double]) { | |
/** | |
* | |
* @param v vertex to get the path for | |
* @return returns error when v is invalid or sequence of edges | |
* which form the path from source vertex to v vertex | |
*/ | |
def pathTo(v: Int): Either[String, Seq[DirectedEdge]] = { | |
@tailrec | |
def go(list: List[DirectedEdge], vv: Int): List[DirectedEdge] = | |
edgeTo(vv) match { | |
case Some(e) => go(e +: list, e.from) | |
case None => list | |
} | |
hasPath(v).map(b => if (!b) Seq() else go(List(), v)) | |
} | |
/** | |
* | |
* @param v vertex to check whether path from source vertex to v vertex exists | |
* @return returns error when v is invalid or Boolean | |
* when some path from source vertex to vertex v exists | |
*/ | |
def hasPath(v: Int): Either[String, Boolean] = | |
distTo.lift(v).map(_ < Double.PositiveInfinity).toRight(s"Vertex $v does not exist") | |
/** | |
* | |
* @param v vertex to get the distance for | |
* @return returns error when v is invalid or | |
* the Double distance which is a sum of weights | |
*/ | |
def distToV(v: Int): Either[String, Double] = | |
distTo.lift(v).toRight(s"Vertex $v does not exist") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment