/*
Divide a given amount into bills and coins using a greedy algorithm.
This program is written in idiomatic Swift, using clear structure,
functions, built‑in methods, and full explanations.
*/
import Foundation
/*
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.
*/
func divideAmount(amount: Int, denominations: [Int]) {
print("Dividing amount: \(amount)\n")
var remaining = amount
for d in denominations {
let count = remaining / d // integer division
if count > 0 {
print("\(d)-unit: \(count)")
remaining %= d // reduce remaining amount
}
}
if remaining > 0 {
print("\nWarning: leftover amount = \(remaining)")
}
}
func main() {
let billsCoins: [Int] = [500, 100, 200, 50, 20, 10, 5, 2, 1]
// Swift: sort descending using sorted(by:)
let denominations: [Int] = billsCoins.sorted(by: >)
let amount: Int = 9749
divideAmount(amount: amount, denominations: denominations)
}
main()
/*
run:
Dividing amount: 9749
500-unit: 19
200-unit: 1
20-unit: 2
5-unit: 1
2-unit: 2
*/