program DivideAmount;
{
Divide a given amount into bills and coins using a greedy algorithm.
This program is written in idiomatic Free Pascal, using clear structure,
functions, and full explanations.
}
{
Procedure: 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.
}
procedure DivideAmount(amount: Integer; const denominations: array of Integer);
var
i: Integer;
d: Integer;
count: Integer;
begin
WriteLn('Dividing amount: ', amount, LineEnding);
for i := 0 to High(denominations) do
begin
d := denominations[i];
count := amount div d; { integer division }
if count > 0 then
begin
WriteLn(d, '-unit: ', count);
amount := amount mod d; { reduce remaining amount }
end;
end;
if amount > 0 then
WriteLn(LineEnding, 'Warning: leftover amount = ', amount);
end;
var
bills_coins: array[0..8] of Integer = (500, 100, 200, 50, 20, 10, 5, 2, 1);
denominations: array of Integer;
i, j, temp: Integer;
amount: Integer;
begin
{ Copy array to dynamic array for sorting }
SetLength(denominations, Length(bills_coins));
for i := 0 to High(bills_coins) do
denominations[i] := bills_coins[i];
{ Sort descending (Free Pascal has no built-in sort for arrays) }
for i := 0 to High(denominations) do
for j := i + 1 to High(denominations) do
if denominations[j] > denominations[i] then
begin
temp := denominations[i];
denominations[i] := denominations[j];
denominations[j] := temp;
end;
amount := 9749;
DivideAmount(amount, denominations);
end.
{
run:
Dividing amount: 9749
500-unit: 19
200-unit: 1
20-unit: 2
5-unit: 1
2-unit: 2
}