Last active
August 12, 2021 08:06
-
-
Save gundamew/c6daff68d15708c60ab33622c72590d5 to your computer and use it in GitHub Desktop.
Get the lowest amount of coins for a given change value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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