Solving Dynamic Programming problems using Functional Programming (Part 1)

Miguel Vilá
Sep 11, 2017 · 6 min read

The imperative perspective

def knapsack(maxWeight: Int, value: Vector[Int], weight: Vector[Int]): Int = {
val n = value.length
val solutions: Array[Array[Int]] = Array.fill(n+1, maxWeight + 1)( 0 )
(1 to n) foreach { i =>
(1 to maxWeight) foreach { j =>
solutions(i)(j) = if( j - weight(i-1) >= 0 ) {
Math.max(
solutions(i-1)(j) ,
solutions(i-1)(j - weight(i-1)) + value(i-1)
)
} else {
solutions(i-1)(j)
}
}
}
solutions(n)(maxWeight)
}
def knapsack(maxWeight: Int, value: Vector[Int], weight: Vector[Int]): Int = {
val n = value.length
var solutions: Array[Int] = Array.fill(maxWeight + 1)( 0 )
(1 to n) foreach { i =>
val newSolutions = Array.fill(maxWeight + 1)( 0 )
(1 to maxWeight) foreach { j =>
newSolutions(j) = if( j - weight(i-1) >= 0 ) {
Math.max(
solutions(j) ,
solutions(j - weight(i-1)) + value(i-1)
)
} else {
solutions(j)
}
}
solutions = newSolutions
}
solutions(maxWeight)
}

How to do the same thing functionally?

What we have seen so far

Additional resources

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade