Skip to content

Instantly share code, notes, and snippets.

@samvaughton
Last active December 27, 2015 16:19
Show Gist options
  • Save samvaughton/7354168 to your computer and use it in GitHub Desktop.
Save samvaughton/7354168 to your computer and use it in GitHub Desktop.
Get the lowest amount of coins for a given change value.
<?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;
}
<?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