Added prim's algorithm and adjacency matrix

This commit is contained in:
Rohan Sircar 2020-04-03 13:46:34 +05:30
parent 67c7dd11d5
commit 192cda5257

View File

@ -1,6 +1,7 @@
import model.Coord
import model.Customer
import model.HHCEdge
import scala.collection.mutable._
object Main {
def main(args: Array[String]): Unit = {
@ -15,6 +16,7 @@ object Main {
val cust3 = Customer(Coord(3, 5), 6)
val cust4 = Customer(Coord(6, 8), 9)
val cust5 = Customer(Coord(5, 4), 6)
val edge1 = HHCEdge(cust1, cust2)
val edge2 = HHCEdge(cust3, cust4)
@ -22,11 +24,91 @@ object Main {
println(s"Edge 1 = ${edge1}")
println(s"Edge 1 weight = ${edge1.weight}")
val V = Array(cust1, cust2, cust3, cust4)
val V = Array(cust1, cust2, cust3, cust4, cust5)
val E = Array(edge1, edge2)
V.foreach(println(_))
// prints
// Customer(Coord(3, 4), 5)
// Customer(Coord(2, 5), 7)
// Customer(Coord(3, 5), 6)
// Customer(Coord(6, 8), 9)
// Customer(Coord(5, 4), 6)
E.foreach(println(_))
//prints
// HHCEdge(Customer(Coord(3, 4), 5), Customer(Coord(2, 5), 7))
// HHCEdge(Customer(Coord(3, 5), 6), Customer(Coord(6, 8), 9))
// sample adjacency
// format: off
val edges = Array(
Array(0 , 9 , 75, 0 , 0),
Array(9 , 0 , 95, 19, 42),
Array(75, 95, 0 , 51, 66),
Array(0 , 19, 51, 0 , 31),
Array(0 , 42, 66, 31, 0)
);
//format: on
// Prim's algorithm
val selected: ArrayBuffer[Boolean] =
ArrayBuffer.from(Array.ofDim[Boolean](5).toIndexedSeq)
selected(0) = true
var numberOfEdges = 0
for (_ <- numberOfEdges to 3) {
var min = 999999
var x = 0
var y = 0
for (i <- 0 to 4) {
if (selected(i) == true) {
for (j <- 0 to 4) {
if (selected(j) == false && edges(i)(j) != 0) {
if (min > edges(i)(j)) {
min = edges(i)(j)
x = i
y = j
}
}
}
}
}
println(s"Edge selected $x - $y : ${edges(x)(y)}")
selected(y) = true
}
// Prim's algorithm result
// Edge selected 0 - 1: 9
// Edge selected 1 - 3: 19
// Edge selected 3 - 4: 31
// Edge selected 3 - 2: 51
// Verify the result with the one at https://www.programiz.com/dsa/prim-algorithm
val edges2: ArrayBuffer[ArrayBuffer[Double]] = ArrayBuffer.empty
// create adjacency matrix from given customers
for (i <- 0 to 4) {
edges2.append(ArrayBuffer.empty)
for (j <- 0 to 4) {
edges2(i).append(HHCEdge(V(i), V(j)).weight)
}
}
println(edges2) // prints adjacency matrix
// ArrayBuffer(
// ArrayBuffer(0.0 , 1.4142135623730951, 1.0 , 5.0 , 2.0),
// ArrayBuffer(1.4142135623730951, 0.0 , 1.0 , 5.0 , 3.1622776601683795),
// ArrayBuffer(1.0 , 1.0 , 0.0 , 4.242640687119285, 2.23606797749979),
// ArrayBuffer(5.0 , 5.0 , 4.242640687119285, 0.0 , 4.123105625617661),
// ArrayBuffer(2.0 , 3.1622776601683795, 2.23606797749979 , 4.123105625617661, 0.0),
// )
}
}