Skip to content

Instantly share code, notes, and snippets.

@gundamew
Last active August 12, 2021 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gundamew/c6daff68d15708c60ab33622c72590d5 to your computer and use it in GitHub Desktop.
Save gundamew/c6daff68d15708c60ab33622c72590d5 to your computer and use it in GitHub Desktop.
Get the lowest amount of coins for a given change value.
<?php
function change_make($price, $pay)
{
if ($price === 0 || $pay === 0 || $price > $pay) {
return;
}
$change = $pay - $price;
return change_coins($change);
}
// Copied from https://gist.github.com/samvaughton/7354168
function change_coins($amount)
{
// Use NTD coins
$denominations = [
'fifty dollars' => 50,
'ten dollars' => 10,
'five dollars' => 5,
'one dollar' => 1,
];
// Will hold the final amounts
$change = [];
foreach ($denominations as $name => $value) {
// Get the max number of times this coin denomination can fit into the amount
$coins = floor($amount / $value);
// Record the amount of coins for that denomination
$change[$name] = $coins;
// If 1 or more of the denomination can fit into the amount
if ($coins > 0) {
// Then minus that value of the total amount
$amount -= ($value * $coins);
}
}
return $change;
}
print_r(change_make(100, 110)); // [0, 1, 0, 0]
print_r(change_make(50, 50)); // [0, 0, 0, 0]
print_r(change_make(50, 66)); // [0, 1, 1, 1]
print_r(change_make(10, 11)); // [0, 0, 0, 1]
print_r(change_make(1, 10)); // [0, 0, 1, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment