Skip to content

Commit 09dd460

Browse files
implemented several Dynamic Programs
1 parent 945c779 commit 09dd460

File tree

6 files changed

+121
-26
lines changed

6 files changed

+121
-26
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package algorithms.dynamic
2+
3+
// Bottom-up dynamic programming approach
4+
def bottomUpDecomposition(prices: Array[Int], n: Int): Int = {
5+
val dp = Array.fill(n + 1)(0) // dp[i] stores the max revenue for length i
6+
7+
for (j <- 1 to n) {
8+
var maxVal = Int.MinValue
9+
for (i <- 0 until j) {
10+
maxVal = Math.max(maxVal, prices(i) + dp(j - i - 1))
11+
}
12+
dp(j) = maxVal
13+
}
14+
15+
dp(n) // Return the max value for the full length
16+
}
17+
18+
@main
19+
def DecMain(): Unit = {
20+
val length = 4
21+
val prices = Array(1, 5, 8, 9)
22+
// Bottom-up approach
23+
val bottomUpResult = bottomUpDecomposition(prices, length)
24+
println(s"Bottom-up result: $bottomUpResult")
25+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package algorithms.dynamic
2+
3+
def maxNonAdjacentWeight(a: Array[Int]): (Int, List[Int]) = {
4+
val n = a.length
5+
if (n == 0) return (0, List())
6+
if (n == 1) return (a(0), List(a(0)))
7+
8+
val dp = Array.fill(n)(0) // DP table for max weight
9+
val sequence = Array.fill(n)(List[Int]()) // Store selected subsequence
10+
11+
// Base cases
12+
dp(0) = a(0)
13+
sequence(0) = List(a(0))
14+
15+
if (n > 1) {
16+
dp(1) = Math.max(a(0), a(1))
17+
sequence(1) = if (a(1) > a(0)) List(a(1)) else List(a(0))
18+
}
19+
20+
// Fill DP table iteratively
21+
for (i <- 2 until n) {
22+
if (dp(i - 1) > dp(i - 2) + a(i)) {
23+
dp(i) = dp(i - 1)
24+
sequence(i) = sequence(i - 1) // Take the previous sequence
25+
} else {
26+
dp(i) = dp(i - 2) + a(i)
27+
sequence(i) = sequence(i - 2) :+ a(i) // Append current element
28+
}
29+
}
30+
31+
(dp(n - 1), sequence(n - 1)) // Return max weight and sequence
32+
}
33+
34+
@main
35+
def runMaxNonAdjacentWeight(): Unit = {
36+
val a = Array(3, 2, 7, 10) // Example input
37+
val (maxWeight, maxSequence) = maxNonAdjacentWeight(a)
38+
39+
println(s"Maximum weight: $maxWeight")
40+
println(s"Selected sequence: $maxSequence")
41+
}
Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,61 @@
11
package algorithms.dynamic
22

3-
case class Matrix(n : Int, m : Int)
3+
case class Matrix(n: Int, m: Int)
44

5-
def optimalMatrixParentheses(lst : Array[Matrix]) : (Int, Array[Array[Int]]) = {
5+
def optimalMatrixParentheses(lst: Array[Matrix]): (Int, Array[Array[Int]]) = {
66
val length = lst.length
7-
val dp : Array[Array[Int]] = Array.fill(length,length)(0)
7+
val dp: Array[Array[Int]] = Array.fill(length, length)(0)
8+
val s: Array[Array[Int]] = Array.fill(length, length)(0)
89

9-
for(i <- 1 until length ){
10-
for(j <- 0 until length - i){
10+
for (i <- 1 until length) {
11+
for (j <- 0 until length - i) {
1112
val index = j + i
1213
dp(j)(index) = Int.MaxValue
13-
for(k <- j until index ){
14-
val q = dp(j)(k) + dp(k+1)(index) + lst(j).n * lst(k).m * lst(index).m
15-
if q < dp(j)(index) then dp(j)(index) = q
14+
for (k <- j until index) {
15+
val q = dp(j)(k) + dp(k + 1)(index) + lst(j).n * lst(k).m * lst(index).m
16+
if (q < dp(j)(index)) {
17+
dp(j)(index) = q
18+
s(j)(index) = k
19+
}
1620
}
17-
//println(s"${dp(j)(index)}")
21+
// println(s"${dp(j)(index)}")
1822
}
1923
}
2024

21-
(dp(0)(length -1 ) , dp)
25+
def printSolution(s: Array[Array[Int]], i: Int, j: Int): Unit = {
26+
if (i == j) {
27+
print(s" A $i ")
28+
} else {
29+
print(" ( ")
30+
printSolution(s, i, s(i)(j))
31+
printSolution(s, s(i)(j) + 1, j)
32+
print(" ) ")
33+
}
34+
}
35+
36+
printSolution(s, 0, length - 1)
37+
println("\n")
38+
39+
(dp(0)(length - 1), dp)
2240
}
2341

2442
@main
25-
def MatrixMain() : Unit = {
26-
val matrixList = Array(Matrix(3,5), Matrix(5,1), Matrix(1,4),Matrix(4,2))
27-
val (num ,res) = optimalMatrixParentheses(matrixList)
43+
def MatrixMain(): Unit = {
44+
val matrixList = Array(Matrix(5, 10), Matrix(10, 3), Matrix(3, 12), Matrix(12, 5), Matrix(5, 60), Matrix(60, 6))
45+
val (num, res) = optimalMatrixParentheses(matrixList)
46+
res.foreach { row =>
47+
println(row.mkString(" "))
48+
}
49+
50+
println(s"The minimal number of scalars is $num ")
51+
}
52+
53+
def MatrixTest(): Unit = {
54+
val matrixList = Array(Matrix(3, 5), Matrix(5, 1), Matrix(1, 4), Matrix(4, 2))
55+
val (num, res) = optimalMatrixParentheses(matrixList)
2856
res.foreach { row =>
2957
println(row.mkString(" "))
3058
}
3159

3260
println(s"The minimal number of scalars is $num ")
33-
}
61+
}

src/main/scala/datastructures/graph/graph.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,4 @@ class Graph[T](val isDirected: Boolean) {
2727
def getEdges: Iterable[Edge[T]] = edges
2828

2929
def getNeighbors(vertex: T): Iterable[(T, Double)] = adjacencyList.getOrElse(vertex, Seq())
30-
}
30+
}

src/main/scala/datastructures/tree/AVLTree.scala

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@ case class AVLTree[T](key: T, left: Option[AVLTree[T]] = None, right: Option[AVL
3636
}
3737

3838
private def createUpdatedNode(
39-
newLeft: Option[AVLTree[T]],
40-
newRight: Option[AVLTree[T]]
41-
): AVLTree[T] = {
39+
newLeft: Option[AVLTree[T]],
40+
newRight: Option[AVLTree[T]]
41+
): AVLTree[T] = {
4242
val newHeight = 1 + Math.max(
4343
newLeft.map(_.height).getOrElse(0),
4444
newRight.map(_.height).getOrElse(0)
@@ -67,13 +67,13 @@ case class AVLTree[T](key: T, left: Option[AVLTree[T]] = None, right: Option[AVL
6767

6868
private def rightRotate()(implicit ord: Ordering[T]): AVLTree[T] = {
6969
val pivot = left.get
70-
val newRight = AVLTree(
70+
val newRight = AVLTree(
7171
key = key,
7272
left = pivot.right,
7373
right = right,
7474
height = 1 + Math.max(pivot.getHeightOfRight, getHeightOfRight)
7575
)
76-
AVLTree(
76+
AVLTree(
7777
key = pivot.key,
7878
left = pivot.left,
7979
right = Some(newRight),
@@ -83,13 +83,13 @@ case class AVLTree[T](key: T, left: Option[AVLTree[T]] = None, right: Option[AVL
8383

8484
private def leftRotate()(implicit ord: Ordering[T]): AVLTree[T] = {
8585
val pivot = right.get
86-
val newLeft = AVLTree(
86+
val newLeft = AVLTree(
8787
key = key,
8888
left = left,
8989
right = pivot.left,
9090
height = 1 + Math.max(getHeightOfLeft, pivot.getHeightOfLeft)
9191
)
92-
AVLTree(
92+
AVLTree(
9393
key = pivot.key,
9494
left = Some(newLeft),
9595
right = pivot.right,

src/main/scala/datastructures/tree/BTree.scala

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ case class BTree[T: Ordering](keys: List[T] = List(), children: List[BTree[T]] =
44

55
def search(value: T): Boolean = {
66
keys match {
7-
case Nil => false
7+
case Nil => false
88
case ks if ks.contains(value) => true
9-
case ks if isLeaf => false
9+
case ks if isLeaf => false
1010
case ks =>
1111
val (left, right) = ks.span(implicitly[Ordering[T]].lt(_, value))
1212
children(left.length).search(value)
@@ -17,7 +17,7 @@ case class BTree[T: Ordering](keys: List[T] = List(), children: List[BTree[T]] =
1717
val (newRoot, maybeSplit) = insertInternal(newKey)
1818
maybeSplit match {
1919
case Some((median, rightNode)) => BTree(List(median), List(newRoot, rightNode), maxKeys)
20-
case None => newRoot
20+
case None => newRoot
2121
}
2222
}
2323

@@ -34,7 +34,8 @@ case class BTree[T: Ordering](keys: List[T] = List(), children: List[BTree[T]] =
3434
maybeSplit match {
3535
case Some((median, rightNode)) =>
3636
val newKeys = (left :+ median) ++ right
37-
val newChildrenWithSplit = (newChildren.take(left.length + 1) :+ rightNode) ++ newChildren.drop(left.length + 1)
37+
val newChildrenWithSplit =
38+
(newChildren.take(left.length + 1) :+ rightNode) ++ newChildren.drop(left.length + 1)
3839
splitIfNeeded(BTree(newKeys, newChildrenWithSplit, maxKeys))
3940
case None => (BTree(keys, newChildren, maxKeys), None)
4041
}

0 commit comments

Comments
 (0)