Recently I challenged my co-worker to write an algorithm to solve this problem:
Find the least number of coins required that can make any change from
After failing to find a good solution to this type of problem in PHP, I developed this function.
It takes any amount of money (up to $999.99) and returns an array of the minimum number of each bill / coin required to get to that value.
It first converts the value to an int in pennies (for some reason I would get errors at the very end when using standard float values).
The returned denominations are also in pennies (ie: 5000 = $50, 100 = $1, etc).
function makeChange($val)
{
$amountOfMoney = intval($val*100);
$cashInPennies = array(10000,5000,2000,1000,500,100,25,10,5,1);
$outputArray = array();
$currentSum = 0;
$currentDenom = 0;
while ($currentSum < $amountOfMoney) {
if( ( $currentSum + $cashInPennies[$currentDenom] ) <= $amountOfMoney ) {
$currentSum = $currentSum + $cashInPennies[$currentDenom];
$outputArray[$cashInPennies[$currentDenom]]++;
} else {
$currentDenom++;
}
}
return $outputArray;
}
$change = 56.93;
$output = makeChange($change);
print_r($output);
echo "
Total number of bills & coins: ".array_sum($output);
=== OUTPUT ===
Array ( [5000] => 1 [500] => 1 [100] => 1 [25] => 3 [10] => 1 [5] => 1 [1] => 3 )
Total number of bills & coins: 11