Will it be closer to what you are trying to do?
case class Container(name:String,count:Long,value:Double) //val target = 742.0 val target = 500.0 val value = 250.0 val a = Container("Resource1", 1 , 250.0) val b = Container("Resource2", 2 , 125.0) val c = Container("Resource3", 3 , 83.33) val d = Container("Resource4", 1 , 250.0) val cList1 = List(a,b,c,d) val a1 = Container("Resource1", 2 , 125.0) val b2 = Container("Resource2", 1 , 250.0) val c3 = Container("Resource3", 3 , 83.33) val d4 = Container("Resource4", 1 , 250.0) val cList2 = List(a1,b2,c3,d4) val a5 = Container("Resource1", 2 , 125.0) val b6 = Container("Resource2", 1 , 250.0) val c7 = Container("Resource3", 1 , 250.0) val d8 = Container("Resource4", 3 , 83.33) val cList3 = List(a5,b6,c7,d8) @tailrec def doRecursion(containerList: List[Container]): List[Container] = { if(containerList.map(_.value).sum <= target) containerList else doRecursion(containerList.map( c => Container(c.name, c.count + 1, c.value/2))) } doRecursion(cList1) doRecursion(cList2) doRecursion(cList3)
And I get the result:
res0: List[Container] = List(Container(Resource1,2,125.0), Container(Resource2,3,62.5), Container(Resource3,4,41.665), Container(Resource4,2,125.0)) res1: List[Container] = List(Container(Resource1,3,62.5), Container(Resource2,2,125.0), Container(Resource3,4,41.665), Container(Resource4,2,125.0)) res2: List[Container] = List(Container(Resource1,3,62.5), Container(Resource2,2,125.0), Container(Resource3,2,125.0), Container(Resource4,4,41.665))
I commented / reduced the old value for target since doRecursion() just returns the original list.