Skip to content

Instantly share code, notes, and snippets.

@renatorib
Last active August 29, 2015 14:24
Show Gist options
  • Save renatorib/e10b4e49a9cf8e9308a6 to your computer and use it in GitHub Desktop.
Save renatorib/e10b4e49a9cf8e9308a6 to your computer and use it in GitHub Desktop.
Printi Test - Class Cash - Minimum notes algorithm
<?php
class Cash {
/**
* Get plain available notes and his quantity (true = infinite)
* Example:
* '100' => 20 // Available 20 notes of 100
* '100' => true // Available infinite notes of 100
*
* @return array
*/
static function availableNotes(){
$notes = [
'100' => true,
'50' => true,
'20' => true,
'10' => true
];
krsort($notes);
return $notes;
}
/**
* Get minimum notes from a value
*
* @param int $value Input value;
* @return array All notes that represent the value
*/
static function getMinNotes($value){
if(!is_int($value) || $value <= 0){
return ['error' => 'InvalidArgumentException'];
}
$availableNotes = Cash::availableNotes();
$return = [];
foreach($availableNotes as $note => $qty){
$note = (string) $note;
$return[$note] = 0;
while($value >= $note && ($qty > 0 || $qty == true)){
if(is_int($qty)){
$qty--;
}
$return[$note]++;
$value -= $note;
}
}
if(!$value == 0){
return ['error' => 'BillUnavaiableException'];
}
return array_filter($return);
}
}
<?php
// Available notes: 100, 50, 20, 10
Cash::getMinNotes(100);
// array(
// "100" => 1
// );
Cash::getMinNotes(2250);
// array(
// "100" => 22,
// "50" => 1
// );
Cash::getMinNotes(260);
// array(
// "100" => 2,
// "50" => 1,
// "10" => 1
// );
Cash::getMinNotes(180);
// array(
// "100" => 1,
// "50" => 1,
// "20" => 1,
// "10" => 1
// );
Cash::getMinNotes(185);
// array(
// "error" => "BillUnavaiableException"
// );
Cash::getMinNotes(-100);
// array(
// "error" => "InvalidArgumentException"
// );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment