bag weight

This commit is contained in:
Ivan Li 2019-01-29 17:22:19 +08:00
parent 89421c0ec4
commit 45758ee438
2 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,25 @@
package ch39_back_tracking
class BagWeight(maxBagItemCount: Int, maxBagWeight: Int) {
def calculateMaxWeight(items: Array[Int]): Int = {
var maxWeight = 0
def _calcMaxWeight(itemIndex: Int, currentWeight: Int): Unit = {
if (currentWeight == maxBagWeight || itemIndex == items.length) {
if (currentWeight > maxWeight) {
maxWeight = currentWeight
}
} else {
//check next item
_calcMaxWeight(itemIndex + 1, currentWeight)
if (currentWeight + items(itemIndex) <= maxBagWeight) {
_calcMaxWeight(itemIndex + 1, currentWeight + items(itemIndex))
}
}
}
_calcMaxWeight(0, 0)
maxWeight
}
}

View File

@ -0,0 +1,15 @@
package ch39_back_tracking
import org.scalatest.FlatSpec
class BagWeightTest extends FlatSpec {
behavior of "BagWeightTest"
it should "calculateMaxWeight" in {
val bagWeight = new BagWeight(5,9)
val maxWeight = bagWeight.calculateMaxWeight(Array(1,2,3,5,6))
println(maxWeight)
}
}