Skip to content

Commit 35ee752

Browse files
authored
Merge pull request #235 from adrianobrito/dijkstra-scala
Adicionar Algoritmo de Dijkstra em Scala
2 parents d958907 + a1a8c43 commit 35ee752

File tree

2 files changed

+64
-2
lines changed

2 files changed

+64
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,8 @@ Com o objetivo de alcançar uma abrangência maior e encorajar mais pessoas a co
112112
</a>
113113
</td>
114114
<td> <!-- Scala -->
115-
<a href="./CONTRIBUTING.md">
116-
<img align="center" height="25" src="./logos/github.svg" />
115+
<a href="./src/scala/Dijkstra.scala">
116+
<img align="center" height="25" src="./logos/scala.svg" />
117117
</a>
118118
</td>
119119
<td> <!-- Kotlin -->

src/scala/Dijkstra.scala

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import scala.annotation.tailrec
2+
3+
trait Path {
4+
def edges: Seq[Edge]
5+
}
6+
7+
case class ExistingPath(edges: Seq[Edge]) extends Path
8+
9+
object EmptyPath extends Path {
10+
override def edges: Seq[Edge] = Seq.empty
11+
}
12+
13+
case class Vertex(id: String)
14+
15+
case class Edge(from: Vertex, to: Vertex, distance: Int)
16+
17+
case class Graph(edges: List[Edge]) {
18+
19+
implicit object EdgesOrdering extends Ordering[Edge] {
20+
def compare(a: Edge, b: Edge) = a.distance compare b.distance
21+
}
22+
23+
@tailrec
24+
final def dijkstra(start: Vertex, pathComposition: Path = EmptyPath): Path = {
25+
val startEdges: Seq[Edge] = edges.filter(_.from == start).sorted
26+
val smallestDistance: Option[Edge] = startEdges
27+
.filter(e => !pathComposition.edges.map(_.from).contains(e.to))
28+
.headOption
29+
30+
smallestDistance match {
31+
case Some(distance) =>
32+
dijkstra(
33+
distance.to,
34+
ExistingPath(edges = pathComposition.edges.appended(distance))
35+
)
36+
case None => pathComposition
37+
}
38+
}
39+
}
40+
41+
object Main extends App {
42+
43+
val startA: Vertex = Vertex("A")
44+
val graph: Graph = Graph(
45+
edges = List(
46+
Edge(from = Vertex("A"), to = Vertex("B"), distance = 1),
47+
Edge(from = Vertex("A"), to = Vertex("C"), distance = 4),
48+
Edge(from = Vertex("B"), to = Vertex("A"), distance = 1),
49+
Edge(from = Vertex("B"), to = Vertex("C"), distance = 2),
50+
Edge(from = Vertex("B"), to = Vertex("D"), distance = 5),
51+
Edge(from = Vertex("C"), to = Vertex("A"), distance = 4),
52+
Edge(from = Vertex("C"), to = Vertex("B"), distance = 2),
53+
Edge(from = Vertex("C"), to = Vertex("D"), distance = 1),
54+
Edge(from = Vertex("D"), to = Vertex("B"), distance = 5),
55+
Edge(from = Vertex("D"), to = Vertex("C"), distance = 1)
56+
)
57+
)
58+
59+
val result: Path = graph.dijkstra(start = startA)
60+
println("Calculating path...")
61+
println(s"Result: ${result.edges}")
62+
}

0 commit comments

Comments
 (0)