Last active
December 27, 2015 16:19
-
-
Save samvaughton/7354168 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 coin_change($amount) { | |
// What us British use... | |
$coinDenominations = array( | |
'Fifty pence' => 50, | |
'Twenty pence' => 20, | |
'Ten pence' => 10, | |
'Five pence' => 5, | |
'Two pence' => 2, | |
'One penny' => 1 | |
); | |
// Will hold the final amounts | |
$change = array(); | |
foreach ($coinDenominations 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; | |
} |
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 | |
// Just a PHPUnit test case for this function. Passes on 3.6.10 of PHPUnit. | |
public function testCoinChange() | |
{ | |
$testStub = array( | |
99 => array(1, 2, 0, 1, 2, 0), | |
50 => array(1, 0, 0, 0, 0, 0), | |
3 => array(0, 0, 0, 0, 1, 1), | |
8 => array(0, 0, 0, 1, 1, 1), | |
1 => array(0, 0, 0, 0, 0, 1), | |
41 => array(0, 2, 0, 0, 0, 1), | |
36 => array(0, 1, 1, 1, 0, 1), | |
); | |
foreach($testStub as $amount => $stub) { | |
$this->assertEquals($stub, array_values(coin_change($amount))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment