From 45758ee4388d27fdfe93ae33122029cc80278093 Mon Sep 17 00:00:00 2001 From: Ivan Li Date: Tue, 29 Jan 2019 17:22:19 +0800 Subject: [PATCH] bag weight --- .../scala/ch39_back_tracking/BagWeight.scala | 25 +++++++++++++++++++ .../ch39_back_tracking/BagWeightTest.scala | 15 +++++++++++ 2 files changed, 40 insertions(+) create mode 100644 scala/src/main/scala/ch39_back_tracking/BagWeight.scala create mode 100644 scala/src/test/scala/ch39_back_tracking/BagWeightTest.scala 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) + } + +}