Advertisement
Guest User

Untitled

a guest
May 24th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. class RubyATM
  2. ACCEPTED_NOTES = [100, 200, 500, 2000]
  3. DEFAULT_BALANCE = { 100 => 10, 200 => 10, 500 => 1, 2000 => 50}
  4. MAX_WITHDRAWAL = 20000
  5. EVIL_ATM = false # Always return the smallest possible notes
  6.  
  7. def initialize(notes = DEFAULT_BALANCE)
  8. @balance = {}
  9. deposit(notes)
  10. end
  11.  
  12. def withdraw(amount)
  13. check_withdrawal(amount)
  14. withdrawal = fetch_notes(amount)
  15. @balance.merge!(withdrawal){ |key, existing, withdrawal| existing - withdrawal }
  16. return withdrawal, @balance
  17. end
  18.  
  19. def deposit(notes)
  20. check_deposit(notes)
  21. @balance.merge!(notes){ |key, existing, deposit| existing + deposit }
  22. end
  23.  
  24. private
  25.  
  26. def fetch_notes(amount)
  27. withdrawn_notes = {}
  28. withdrawn_amount = 0
  29.  
  30. notes = EVIL_ATM ? @balance.keys.sort : @balance.keys.sort.reverse
  31. notes.each do |note|
  32. max_notes = (amount - withdrawn_amount) / note
  33. actual_notes = [@balance[note], max_notes].min
  34. if actual_notes > 0
  35. withdrawn_amount += actual_notes * note
  36. withdrawn_notes[note] = actual_notes
  37. end
  38. end
  39.  
  40. raise WithdrawalAmountInvalid, 'Amount cannot be withdrawn. Please specify another amount.' if withdrawn_amount < amount
  41.  
  42. withdrawn_notes
  43. end
  44.  
  45. def check_withdrawal(amount)
  46. raise WithdrawalAmountInvalid, 'Please round to the nearest tenth.' if amount % 10 > 0
  47. raise WithdrawalAmountTooLow, 'Amount too low.' if amount < 0
  48. raise WithdrawalAmountTooHigh, "Amount too high. Max withdrawal can be #{max_withdrawal}." if amount > max_withdrawal
  49. end
  50.  
  51. def check_deposit(notes)
  52. raise DepositAmountInvalid, "This ATM accepts only these notes: #{ACCEPTED_NOTES.join(", ")}" unless (notes.keys - ACCEPTED_NOTES).empty?
  53. end
  54.  
  55. def balance
  56. @balance.map{ |note, count| note * count }.reduce(:+)
  57. end
  58.  
  59. def max_withdrawal
  60. [MAX_WITHDRAWAL, balance].min
  61. end
  62. end
  63.  
  64. class WithdrawalAmountTooHigh < StandardError; end
  65. class WithdrawalAmountTooLow < StandardError; end
  66. class WithdrawalAmountInvalid < StandardError; end
  67. class DepositAmountInvalid < StandardError; end
  68.  
  69. module Run
  70. loop do
  71. puts"\n"
  72. puts"-----------------------------------"
  73. print"Enter the amount you need to withdrawl: "
  74. amount = gets.chomp.to_i
  75. puts"-----------------------------------"
  76. atm = RubyATM.new
  77. currency_calculation, balance = atm.withdraw(amount)
  78. p "Currency calculation=> ",currency_calculation
  79. p "Balance remaining in ATM: #{balance}"
  80. break
  81. end
  82. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement