fork(7) download
  1. <?php
  2.  
  3.  
  4. $amount = 240;
  5.  
  6. $bills = array(
  7. 10 => 10,
  8. 50 => 10,
  9. 100 => 10,
  10. 500 => 10,
  11. );
  12.  
  13. $keysBills = array_keys($bills);
  14.  
  15. $attempts = 0;
  16.  
  17. function countBillsSum($billsCopy) {
  18.  
  19. $valuesBillsCopy = array_values($billsCopy);
  20. $keysBillsCopy = array_keys($billsCopy);
  21.  
  22. for($i = 0; $i < count($billsCopy); $i++) {
  23. $result[$i] = $valuesBillsCopy[$i] * $keysBillsCopy[$i];
  24. }
  25. $result = array_sum($result);
  26. return $result;
  27. }
  28.  
  29. function findChange($amount, $keysBills, $bills, $billNumber) {
  30.  
  31. $x = null;
  32. $debugOffset = str_repeat(" ", 3 - $billNumber);
  33. //echo "{$debugOffset}enter $billNumber\n";
  34.  
  35. global $attempts;
  36.  
  37. $currentBill = $keysBills[$billNumber];
  38.  
  39. $currentMaxBills = min(floor($amount / $keysBills[$billNumber]), $bills[$currentBill]);
  40.  
  41. $amount = $amount - $currentBill*$currentMaxBills;
  42.  
  43. for ($i = $currentMaxBills; $i >= 0; $i--) {
  44.  
  45. $attempts++;
  46. $billsCopy = $bills;
  47. $billsCopy[$currentBill] = $i;
  48.  
  49. $sum = countBillsSum($billsCopy);
  50. //echo "{$debugOffset} i=$i, bills ".implode(", ", $billsCopy).", sum=$sum\n";
  51.  
  52. if ($billNumber > 0) {
  53. $x = findChange($amount, $keysBills, $billsCopy, $billNumber - 1);
  54. if ($x) {
  55. return $x;
  56. }
  57. } elseif ($amount == 0) {
  58. //echo "{$debugOffset} MATCH ".implode(", ", array_values($billsCopy))." (sum=$sum)\n";
  59. $x = implode(", ", array_values($billsCopy));
  60. return $x;
  61. }
  62. }
  63. }
  64.  
  65. echo findChange($amount, $keysBills, $bills, 3);
  66. echo "\n".$attempts;
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
4, 0, 2, 0
4