Change.class.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. class Change
  3. {
  4. /**
  5. *
  6. * @var 每多少盖子换一瓶汽水
  7. */
  8. public $capUnit;
  9. /**
  10. *
  11. * @var 每多少空瓶换一瓶汽水
  12. */
  13. public $bottelUnit;
  14. /**
  15. *
  16. * @var 总共金额
  17. */
  18. public $money;
  19. /**
  20. *
  21. * @var 汽水单价
  22. */
  23. public $unit;
  24. /**
  25. *
  26. * @var 总共能喝多少汽水
  27. */
  28. public $sum;
  29. public function __construct()
  30. {
  31. $this->money = 10;
  32. $this->unit = 2;
  33. $this->capUnit = 4;
  34. $this->bottelUnit = 2;
  35. }
  36. protected function capToWater($cap)
  37. {
  38. return intval($cap / $this->capUnit);
  39. }
  40. protected function capLeft($cap)
  41. {
  42. return $cap % $this->capUnit;
  43. }
  44. protected function bottleToWater($bottle)
  45. {
  46. return intval($bottle / $this->bottelUnit);
  47. }
  48. protected function bottelLeft($bottle)
  49. {
  50. return $bottle % $this->bottelUnit;
  51. }
  52. public function doCal()
  53. {
  54. $this->sum = intval($this->money / $this->unit);
  55. return $this->cal($this->sum, 0, 0, 0);
  56. }
  57. protected function cal($num, $lastNum, $left_cap, $left_bottle)
  58. {
  59. $cap = $num + $left_cap;
  60. $bottle = $num + $left_bottle;
  61. $capToWater = $this->capToWater($cap);
  62. $bottleToWater = $this->bottleToWater($bottle);
  63. $getWater = $capToWater + $bottleToWater;
  64. $this->sum += $getWater;
  65. $left_cap = $this->capLeft($cap);
  66. $left_bottle = $this->bottelLeft($bottle);
  67. $capToWater_next = $this->capToWater($getWater + $left_cap);
  68. $bottleToWater_next = $this->bottleToWater($getWater + $left_bottle);
  69. if ($capToWater_next || $bottleToWater_next) {
  70. $getWater = $this->cal($getWater, $num, $left_cap, $left_bottle);
  71. }
  72. return $this->sum;
  73. }
  74. }
  75. $c = new Change();
  76. echo $c->doCal();