Just out of curiosity I decided to try and find a solution. It was much simpler than I thought. You would obviously need to have the "inventory" of the ATM with what denomination of bills are available and the quantities. Then you also have the requested amount. You simply need to loop through the available denominations from highest to lowest and determine how many of that denomination will "fit" within the requested amount and apply the minimum of that or the available quantity. You would also want a check at the end of the loop to determine if the requested amount was met (there may not be enough cash or the requested amount is not obtainable, e.g. $31).
Here is a PHP solution. I made the $inventory a hard coded array for testing which would need to be dynamic.I also used global in the function (which I typically avoid) only for the purpose of brevity in the code - a class would probably be a better solution.
<?php
//Array pf possible denominations and their available qty
$inventory = array(
'50' => 3,
'20' => 2,
'10' => 5,
'5' => 10
);
function getCurrency($requestAmt)
{
global $inventory;
//Ensure inventory is from high to low denomination
krsort($inventory);
$distribution = array();
$newInventory = $inventory;
foreach($newInventory as $denom => $quantity)
{
//Determine number of bill of this denom
$denomQty = min($newInventory[$denom], floor($requestAmt/$denom));
//Update distribution and inventory
$distribution[$denom] = $denomQty;
$newInventory[$denom] -= $denomQty;
//Reduce requested amount
$requestAmt -= $denomQty * $denom;
}
//If unable to meet distribution, return error
if($requestAmt != 0)
{
return false;
}
//Return distribution result (removing unused denoms)
$inventory = $newInventory;
return $distribution;
}
################
## TESTING LOGIC
################
$requestedAmounts = array(100, 32, 50, 25, 10, 50, 100, 20, 40);
$header = "<tr><th></th>\n";
foreach(array_keys($inventory) as $denom)
{
$header .= "<th>\${$denom}</th>";
}
$header .= "<th>Total</th></tr>\n";
foreach($requestedAmounts as $amt)
{
echo "<br><br><table border='1'>\n";
echo "<tr><th colspan='6'>Requested amount: $ {$amt}<th></tr>\n";
echo $header;
displayCurrencyRow("Current Inventory", $inventory);
$distribution = getCurrency($amt);
if(!$distribution)
{
echo "<tr><td colspan='6'>Unable to fulfill request</td></tr>\n";
}
else
{
displayCurrencyRow("Distributed Amount", $distribution);
displayCurrencyRow("Remianing Inventory", $inventory);
}
echo "</table>\n";
}
function displayCurrencyRow($label, $amounts)
{
$total = 0;
echo "<tr>\n";
echo "<td>$label</td>\n";
foreach($amounts as $denom => $qty)
{
echo "<td>$qty</td>\n";
$total += $denom * $qty;
}
echo "<td>\${$total}</td>\n";
echo "<tr>\n";
}
?>