Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ Com o objetivo de alcançar uma abrangência maior e encorajar mais pessoas a co
</a>
</td>
<td> <!-- Scala -->
<a href="./CONTRIBUTING.md">
<img align="center" height="25" src="./logos/github.svg" />
<a href="./src/scala/Dijkstra.scala">
<img align="center" height="25" src="./logos/scala.svg" />
</a>
</td>
<td> <!-- Kotlin -->
Expand Down
62 changes: 62 additions & 0 deletions src/scala/Dijkstra.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import scala.annotation.tailrec

trait Path {
def edges: Seq[Edge]
}

case class ExistingPath(edges: Seq[Edge]) extends Path

object EmptyPath extends Path {
override def edges: Seq[Edge] = Seq.empty
}

case class Vertex(id: String)

case class Edge(from: Vertex, to: Vertex, distance: Int)

case class Graph(edges: List[Edge]) {

implicit object EdgesOrdering extends Ordering[Edge] {
def compare(a: Edge, b: Edge) = a.distance compare b.distance
}

@tailrec
final def dijkstra(start: Vertex, pathComposition: Path = EmptyPath): Path = {
val startEdges: Seq[Edge] = edges.filter(_.from == start).sorted
val smallestDistance: Option[Edge] = startEdges
.filter(e => !pathComposition.edges.map(_.from).contains(e.to))
.headOption

smallestDistance match {
case Some(distance) =>
dijkstra(
distance.to,
ExistingPath(edges = pathComposition.edges.appended(distance))
)
case None => pathComposition
}
}
}

object Main extends App {

val startA: Vertex = Vertex("A")
val graph: Graph = Graph(
edges = List(
Edge(from = Vertex("A"), to = Vertex("B"), distance = 1),
Edge(from = Vertex("A"), to = Vertex("C"), distance = 4),
Edge(from = Vertex("B"), to = Vertex("A"), distance = 1),
Edge(from = Vertex("B"), to = Vertex("C"), distance = 2),
Edge(from = Vertex("B"), to = Vertex("D"), distance = 5),
Edge(from = Vertex("C"), to = Vertex("A"), distance = 4),
Edge(from = Vertex("C"), to = Vertex("B"), distance = 2),
Edge(from = Vertex("C"), to = Vertex("D"), distance = 1),
Edge(from = Vertex("D"), to = Vertex("B"), distance = 5),
Edge(from = Vertex("D"), to = Vertex("C"), distance = 1)
)
)

val result: Path = graph.dijkstra(start = startA)
println("Calculating path...")
println(s"Result: ${result.edges}")
}