Last active
June 28, 2017 13:41
-
-
Save bmarcot/5983672 to your computer and use it in GitHub Desktop.
The Knapsack Problem, in Scala -- Keywords: dynamic programming, recursion, scala.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Elegant solution but when I try to use it with List((1, 1500), (2, 2000), (4, 4000)) it returns wrong answer