Skip to content

Instantly share code, notes, and snippets.

@reevik
Last active August 29, 2015 14:18
Show Gist options
  • Save reevik/4d35d0e89d9095f0f7fb to your computer and use it in GitHub Desktop.
Save reevik/4d35d0e89d9095f0f7fb to your computer and use it in GitHub Desktop.
Knapsack using dynamic programming.
object Knapsack {
val W = 10000 // capacity
val n = 100 // number of items
val file = "path-to-your-file-contains-<size> <weight> lines"
val c = Array.ofDim[Int](n, W)
val lines = Source.fromFile(file).getLines.drop(1).toList.map(_.split(" ").map(_.toInt))
def main(args: Array[String]) {
0 until W foreach { x => c(0)(x) = 0 }
for (i <- 1 until n; x <- 0 until W) c(i)(x) = math.max(c(i - 1)(x), { if (lines(i)(1) > x) 0 else c(i - 1)(x - lines(i)(1)) + lines(i)(0) })
print(c(n-1)(W-1))
}
/*
your text file should contain the lines
[knapsack_size][number_of_items]
[value_1] [weight_1]
[value_2] [weight_2]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment