/**
* Divide a given amount into bills and coins using a greedy algorithm.
* This program is written in idiomatic JavaScript, using built‑in methods,
* clear structure, and full explanations.
*/
/**
* Given an amount and a list of bills/coins, print how many
* of each denomination are needed using a greedy algorithm.
*
* The greedy method is optimal for standard currency systems.
*/
function divideAmount(amount, denominations) {
console.log(`Dividing amount: ${amount}\n`);
for (const d of denominations) {
const count = Math.floor(amount / d); // integer division
if (count > 0) {
console.log(`${d}-unit: ${count}`);
amount %= d; // reduce remaining amount
}
}
if (amount > 0) {
console.log(`\nWarning: leftover amount = ${amount}`);
}
}
function main() {
const bills_coins = [500, 100, 200, 50, 20, 10, 5, 2, 1];
// JavaScript: sort descending using .sort()
const denominations = bills_coins.sort((a, b) => b - a);
const amount = 9749;
divideAmount(amount, denominations);
}
main();
/*
run:
Dividing amount: 9749
500-unit: 19
200-unit: 1
20-unit: 2
5-unit: 1
2-unit: 2
*/