Solving subset sum with dynamic programming Dynamic programming is a generic method of…
- User
Solving subset sum with dynamic programming Dynamic programming is a generic method of solving a problem instance by breaking it into smaller sub-instances and then combining the results to a result of the original instance. It differs from divide and conquer in that the sub-instances are overlapping and thus their results can be memoized and not computed again and again. In this exercise, your task is to introduce yourself to dynamic programming and implement an algorithm that solves the subset sum problem with dynamic programming. To get started, you may take a look at the dynamic programming and subset sum pages in wikipedia. Note that dynamic programming technique works well on subset sum problem instances in which the number of all possible subset sums is reasonable small (in the order of millions): even though a set s can have an enormous amount of subsets, many of these subsets can in fact sum up the same value. For instance, if s = {2, 5, 3, 4, 7, 8, 9, 10,....}, then there are at least four subsets summing to 24: {2, 5, 7, 10}, {2, 5, 8, 9}, {3, 4, 7, 10}, and {3, 4, 8, 9}. Dynamic programming exploits this fact by remembering, for instance, that there is a subset {2, 5, 7, 10} summing to the value 24 and does not need to explore the other subsets. Of course, one does not want to store all these subsets explicitly but with minimal amount of information (for instance, for the value 24 one only needs to remember that there is a subset summing to that value and that subset was obtained by adding 10 to another subset [summing up to the value 24 – 10 = 14]).
Use scala 3. Replace the ??? symbol with your solution, do not use external libraries.
Code: package object subsetsumDynProg:
/**
- Solve the subset sum problem with dynamic programming.
- Dynamic programming works in cases where the amount of sums that can be formed is
- still reasonable (in the order of millions). */ def solve(set: Set[Int], target: Int): Option[Set[Int]] = ??? end solve
/*
- The rest of the code includes the recursive backtracking search version
- given in the course material.
- This is only for reference, you don't need to use or modify it in any way. / /* Select an arbitrary element in s */ def selectElementSimple(s: Set[Int], t: Int) = require(!s.isEmpty) s.head end selectElementSimple
/** Select an element in s in a greedy way */ def selectElementGreedy(s: Set[Int], t: Int) = require(!s.isEmpty) if t > 0 then s.max else s.min end selectElementGreedy
/**
- Solve the subset sum problem with recursion.
- The argument function heuristics is a function that, when called with
- a non-empty set s and value t, returns an element in s. */ def solveBacktrackingSearch(set: Set[Int], target: Int, elementSelector: (Set[Int], Int) => Int = selectElementSimple): Option[Set[Int]] =
- Assistant
package object subsetsumDynProg:
/**
- Solve the subset sum problem with dynamic programming.
- Dynamic programming works in cases where the amount of sums that can be formed is
- still reasonable (in the order of millions). */ def solve(set: Set[Int], target: Int): Option[Set[Int]] = // Initialize the dp array val n = set.size val arr = set.toArray val dp = Array.ofDim[Boolean](n + 1, target + 1) for i <- 0 to n do dp(i)(0) = true
for i <- 1 to n dofor j <- 1 to target do dp(i)(j) = dp(i-1)(j) if (j >= arr(i-1)) then dp(i)(j) = dp(i)(j) || dp(i-1)(j-arr(i-1)) // If dp(n)(target) is not true, there is no solution if (!dp(n)(target)) then None else // Traceback the solution val solution = scala.collection.mutable.Set[Int]() var (i, j) = (n, target) while (i > 0 && j > 0) do if (dp(i-1)(j-arr(i-1)) && j >= arr(i-1)) then solution += arr(i-1) j -= arr(i-1) i -= 1 Some(solution.toSet) end ifend solve Initial lines of code should stay untouched. For testing you can use the following: // import subsetsumDynProg._
- User
with val arr = set.toArray val n = arr.length val dp = Array.ofDim[Boolean](n + 1, target + 1)
for (i <- 0 to n) { dp(i)(0) = true } for (i <- 0 until n) { // Updated loop indices for (j <- 0 to target) { // Updated loop indices dp(i + 1)(j) = dp(i)(j) if (j >= arr(i) && dp(i)(j - arr(i))) { // Fixed indexing dp(i + 1)(j) = true } } } if (!dp(n)(target)) { None } else { val solution = scala.collection.mutable.Set[Int]() var (i, j) = (n, target) while (i > 0 && j > 0) { if (j >= arr(i - 1) && dp(i - 1)(j - arr(i - 1))) { // Fixed indexing solution += arr(i - 1) j -= arr(i - 1) } i -= 1 } Some(solution.toSet) }} error: DynProgSpec solve
- should correctly solve some small sets *** FAILED *** java.lang.ArrayIndexOutOfBoundsException: Index 11 out of bounds for length 11 at subsetsumDynProg.package2anonfunmcVImcVI.solve(subsetsumDynProg.scala:41) at subsetsumDynProg.DynProgSpec.testFun1(subsetsumDynProg.spec.scala:24) at subsetsumDynProg.DynProgSpec.1(subsetsumDynProg.spec.scala:23) at org.scalatest.Transformer.apply$$anonfun$1(Transformer.scala:22) ...
- Assistant
I apologize for the mistake in the loop indices. If the previous change didn't work, please try changing the loop indices back and just fixing the indexing as shown below:
def solve(set: Set[Int], target: Int): Option[Set[Int]] = val arr = set.toArray val n = arr.length val dp = Array.ofDim[Boolean](n + 1, target + 1) for (i <- 0 to n) { dp(i)(0) = true } for (i <- 1 to n) { for (j <- 1 to target) { dp(i)(j) = dp(i-1)(j) if (j >= arr(i-1)) then dp(i)(j) = dp(i)(j) || dp(i-1)(j-arr(i-1)) } } if (!dp(n)(target)) { None } else { val solution = scala.collection.mutable.Set[Int]() var (i, j) = (n, target) while (i > 0 && j > 0) { if (dp(i-1)(j-arr(i-1)) && j >= arr(i-1)) { solution += arr(i-1) j -= arr(i-1) } i -= 1 } Some(solution.toSet) } end solveYou can test this solution again with the same test cases as before:
import subsetsumDynProg._ val set = Set(3, 34, 4, 12, 5, 2) val target = 9 val result = solve(set, target) println(s"The solution is: $result")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.