Skip to content

Instantly share code, notes, and snippets.

@bmarcot
Last active June 28, 2017 13:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bmarcot/5983672 to your computer and use it in GitHub Desktop.
Save bmarcot/5983672 to your computer and use it in GitHub Desktop.
The Knapsack Problem, in Scala -- Keywords: dynamic programming, recursion, scala.
def knapsack_aux(x: (Int, Int), is: List[Int]): List[Int] = {
for {
w <- is.zip(is.take(x._1) ::: is.take(is.size - x._1).map(_ + x._2))
} yield math.max(w._1, w._2)
}
def knapsack_rec(xs: List[(Int, Int)], is: List[Int]): List[List[Int]] = {
xs match {
case x :: xs => knapsack_aux(x, is) :: knapsack_rec(xs, knapsack_aux(x, is))
case _ => Nil
}
}
/* knapsack(): return the value inside the knapsack
* xs: list of items, pair of (weight, value)
* k: size of the knapsack
*/
def knapsack(xs: List[(Int, Int)], k: Int): Int = {
knapsack_rec(xs, List.fill(k)(0)).last.last
}
println(knapsack(List((1, 1), (2, 2)), 4))
println(knapsack(List((1, 1), (2, 2)), 5))
println(knapsack(List((1, 1), (2, 2), (2, 4)), 5))
@hadielmougy
Copy link

Elegant solution but when I try to use it with List((1, 1500), (2, 2000), (4, 4000)) it returns wrong answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment