CALC CHANGE

master
E. Almqvist 3 years ago
parent a92eb97ee4
commit ecbc46a5d2
  1. 68
      prog2/coffeemachine/coffeemachine.rb

@ -1,6 +1,8 @@
#!/usr/bin/ruby #!/usr/bin/ruby
class CoffeMachine class CoffeMachine
attr_accessor :location, :change, :coffees, :price, :number_served
def initialize(location, change, coffees, price) def initialize(location, change, coffees, price)
@location = location @location = location
@change = change @change = change
@ -16,7 +18,7 @@ class CoffeMachine
puts("Total amount served: #{@number_served}") puts("Total amount served: #{@number_served}")
print("Insert coins: ") print("Insert coins: ")
coins = await_payment() await_payment()
else else
puts("Inget kaffe kvar :(") puts("Inget kaffe kvar :(")
end end
@ -32,18 +34,9 @@ class CoffeMachine
x = t.split(":") x = t.split(":")
coin_hash[x[0].to_i] = x[1].to_i coin_hash[x[0].to_i] = x[1].to_i
end end
@change = @change.merge(coin_hash) @change = @change.merge(coin_hash)
sum, d = verify_payment(coin_hash) verify_payment(coin_hash)
if( d > 0 ) then
dispense_change(d)
dispense_coffe()
elsif( d < 0 ) then
puts("Not enough money")
else
dispense_coffe()
end
end end
private def verify_payment(coin_hash) private def verify_payment(coin_hash)
@ -51,32 +44,39 @@ class CoffeMachine
coin_hash.each do |key, value| coin_hash.each do |key, value|
sum += value*key sum += value*key
end end
delta = sum - @price
return sum, sum - @price if( delta > 0 ) then
dispense_change(delta)
dispense_coffe()
elsif( delta < 0 ) then
puts("Not enough money")
else
dispense_coffe()
end
end end
private def calculate_change(d)
@change.each do |type, amount| private def calculate_change(delta)
amount = d.to_f/type coin_return = {}
@change.each do |type, count|
if( amount.to_i == amount && amount <= @change[type] ) then puts("adhfio: #{type} #{count}")
return type, amount.to_i amount = delta/type
else
next coin_return[type] = amount
end @change[type] -= amount
delta %= type
next
end end
return nil, nil
return coin_return
end end
private def dispense_change(d) private def dispense_change(delta)
cointype, amount = calculate_change(d) coin_return = calculate_change(delta)
if( cointype ) then puts("Här är din change:")
puts("Här är din change:") puts("-> #{coin_return}")
@change[cointype] -= amount
puts("-> #{amount}st #{cointype} kr")
else
puts("Kan ej ge tillbaka någon change, tack för pengarna.")
end
end end
private def dispense_coffe() private def dispense_coffe()
@ -90,5 +90,5 @@ class CoffeMachine
end end
end end
x = CoffeMachine.new("hej", {10=>2, 1=>100}, 5, 10) x = CoffeMachine.new("hej", {10=>2, 1=>100}, 5, 15)
x.prompt_for_payment x.prompt_for_payment

Loading…
Cancel
Save