diff --git a/scala/src/main/scala/ch39_back_tracking/BagWeight.scala b/scala/src/main/scala/ch39_back_tracking/BagWeight.scala new file mode 100644 index 0000000..bfc5c21 --- /dev/null +++ b/scala/src/main/scala/ch39_back_tracking/BagWeight.scala @@ -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 + } +} diff --git a/scala/src/test/scala/ch39_back_tracking/BagWeightTest.scala b/scala/src/test/scala/ch39_back_tracking/BagWeightTest.scala new file mode 100644 index 0000000..870754b --- /dev/null +++ b/scala/src/test/scala/ch39_back_tracking/BagWeightTest.scala @@ -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) + } + +}