clog14
clog14

Reputation: 1641

Increasing counter in for loop

I have a scala code looking like this

object Main {
  def countChangeIter(money: Int, coins: List[Int], counter: Int): Int=

    if (money == 0)  1
    else if (money < 0)  0
    else {
      for (i <- coins.indices) {
      counter = counter + countChangeIter(money - coins(i), coins.drop(i), 0)


  }

    return counter
}


  def countChange(money: Int, coins: List[Int]): Int = countChangeIter(money, coins, 0)


}

The issue is with the counter = counter... statement. How can I implement that the counter changes by the sum of the old counter and whatever countChangeIter returns?

many thanks c14

Upvotes: 0

Views: 165

Answers (1)

Sam Upra
Sam Upra

Reputation: 737

You can do something like this :

 object Main {
      def countChangeIter(money: Int, coins: List[Int], counter: Int): Int=

        if (money == 0)  1
        else if (money < 0)  0
        else {
          var myCounter = counter
          for (i <- coins.indices) {
          myCounter = myCounter + countChangeIter(money - coins(i), coins.drop(i), 0)


      }

        return myCounter
    }


      def countChange(money: Int, coins: List[Int]): Int = countChangeIter(money, coins, 0)


    }

Bear in mind that if you need to do this in a functional programming setting.. there's probably something wrong with the way the code is structured.

Upvotes: 2

Related Questions