bag weight
This commit is contained in:
parent
89421c0ec4
commit
45758ee438
25
scala/src/main/scala/ch39_back_tracking/BagWeight.scala
Normal file
25
scala/src/main/scala/ch39_back_tracking/BagWeight.scala
Normal 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
|
||||||
|
}
|
||||||
|
}
|
15
scala/src/test/scala/ch39_back_tracking/BagWeightTest.scala
Normal file
15
scala/src/test/scala/ch39_back_tracking/BagWeightTest.scala
Normal 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user