How to divide a given amount into bills (banknotes) and coins in Scala

1 Answer

0 votes
/*
  Divide a given amount into bills and coins using a greedy algorithm.
  This program is written in idiomatic Scala 3, using clear structure,
  functions, built‑in methods, and full explanations.
*/

object DivideAmountApp:

  /*
    Function: divideAmount
    ----------------------
    Given an amount and a list of bills/coins, prints how many
    of each denomination are needed using a greedy algorithm.

    The greedy method is optimal for standard currency systems.
  */
  def divideAmount(amount: Int, denominations: List[Int]): Unit =
    println(s"Dividing amount: $amount\n")

    var remaining = amount

    for d <- denominations do
      val count = remaining / d   // integer division
      if count > 0 then
        println(s"$d-unit: $count")
        remaining %= d            // reduce remaining amount

    if remaining > 0 then
      println(s"\nWarning: leftover amount = $remaining")


  def main(args: Array[String]): Unit =

    val bills_coins: List[Int] = List(500, 100, 200, 50, 20, 10, 5, 2, 1)

    // Scala 3 descending sort (requires explicit `using`)
    val denominations: List[Int] =
      bills_coins.sorted(using Ordering[Int].reverse)

    val amount: Int = 9749

    divideAmount(amount, denominations)


/*
run:

Dividing amount: 9749

500-unit: 19
200-unit: 1
20-unit: 2
5-unit: 1
2-unit: 2

*/

 



answered Jul 26 by avibootz
...