kotlinfor-loopmutablelist

how to perform dynamic subtraction of a list of numbers with a specific value


My idea is to subtract each value from my list through the value of a variable, for example:

var subtraction = 250
var list = mutableListOf(300, 200, 100)

Then, using the 250 of the subtraction variable, you can dynamically subtract each value of the item, from the last to the first, so with that 250 the program should return: -> list(300, 50). Where 250 is subtracted from item 100 (last item) and then "150" remains from the value "250", and the remaining 150 is subtracted from 200 (second item) and remains 50, thus zeroing out the value of "250" and the program stop. Getting (300, 50) -> 50 which comes from 200 (second item). As if I was going through my list of numbers, subtracting item by item through the value of a variable, from last to first.


Solution

  • Your question still needs further clarification:

    The following can be a starting point to solve your question:

    fun subtraction() {
      var subtraction = 250
      var list = mutableListOf(300, 200, 100)
      // Loop the list in Reverse order
      for (number in list.indices.reversed()) {
        subtraction -= list[number] // Subtract the last number
        // If subtraction is greater than zero, continue and remove the last element
        if (subtraction > 0)
          list.removeAt(number)
        else {
          // It subtraction is less than or equal to zero, 
          // remove the last element, append the final subtraction result, 
          // and stop the loop
          list.removeAt(number)
          list.add(abs(subtraction))
          break
        }
      }
      // If the subtraction result is still positive after whole list has been processed, 
      // append it back to the list
      // if (subtraction > 0)
      //   list.add(subtraction)
      println(list)
    }
    

    Output

    [300, 50]