/*
* Function: divideAmount
* ----------------------
* Given an amount and an array of bills/coins, prints how many
* of each denomination are needed using a greedy algorithm.
*
* The greedy method is optimal for standard currency systems.
*/
function divideAmount(int $amount, array $denominations): void
{
echo "Dividing amount: $amount\n\n";
foreach ($denominations as $d) {
$count = intdiv($amount, $d); // idiomatic integer division
if ($count > 0) {
echo "{$d}-unit: $count\n";
$amount %= $d; // reduce remaining amount
}
}
if ($amount > 0) {
echo "\nWarning: leftover amount = $amount\n";
}
}
$bills_coins = [500, 100, 200, 50, 20, 10, 5, 2, 1];
// PHP: sort descending using rsort()
rsort($bills_coins);
$amount = 9749;
divideAmount($amount, $bills_coins);
/*
run:
Dividing amount: 9749
500-unit: 19
200-unit: 1
20-unit: 2
5-unit: 1
2-unit: 2
*/