fork(2) download
  1. <?php
  2.  
  3. /*Given data*/
  4. $amount = 6600;
  5.  
  6. $bills = array(
  7. 100 => 23,
  8. 200 => 3,
  9. 500 => 1,
  10. 1000 => 0,
  11. 2000 => 4,
  12. 5000 => 1
  13. );
  14.  
  15. /*Calculate resulting greenbacks*/
  16. function countResult($amount, $arr)
  17. {
  18. $greenback = array_reverse(array_keys($arr));
  19. $result = array();
  20. foreach ($greenback as $item) {
  21. $count = 0;
  22. $res = 0;
  23. while ($count < $arr[$item] && $res <= $amount) {
  24. $res += $item;
  25. $count = $res / $item - 1;
  26. }
  27. $result[$item] = $count;
  28. $amount = $amount - $item * $count;
  29. }
  30. return array_filter( $result ); # remove values equal to 0
  31. }
  32.  
  33. /*Check for undefined possibilities*/
  34. function checker($amount, $arr)
  35. {
  36. $availableSum = 0;
  37. foreach ($arr as $greenback => $count) {
  38. $availableSum += $greenback * $count;
  39. }
  40. $errorMsg = "";
  41. if ($amount < 0) {
  42. $errorMsg .= "сумма меньше нуля (0)";
  43. } elseif ($amount % 100 !== 0 ) {
  44. $errorMsg .= "сумма не кратна ста (100)";
  45. } elseif ($amount > $availableSum) {
  46. $errorMsg .= "в банкомате недостаточно купюр";
  47. } else {
  48. $errorMsg = null;
  49. }
  50. return $errorMsg;
  51. }
  52.  
  53.  
  54. /*View results*/
  55. function viewer($amount, $arr)
  56. {
  57. print "Сумма: $amount";
  58. print "\n";
  59. if (checker($amount, $arr) !== null) {
  60. print "Выдача невозможна:" . checker($amount, $arr);
  61. } else {
  62. print "Выдача возможна, число купюр:";
  63. print "\n";
  64. foreach (countResult($amount, $arr) as $key => $val) {
  65. print $key . "x" . $val . "\t";
  66. }
  67. }
  68. }
  69.  
  70. /*Testing*/
  71. viewer($amount, $bills);
Success #stdin #stdout 0.02s 20568KB
stdin
Standard input is empty
stdout
Сумма: 6600
Выдача возможна, число купюр:
5000x1	500x1	200x3	100x5