Vending machine change problem (Ruby)

I am working on the below problem:
Write a method to calculate change from a vending machine. Please refer to the actual note and coin in Australia, and each can drink cost $1.6.

Sample Input:

Please enter note or coin (0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10 or 20): 1
Please enter note or coin (0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10 or 20): 1

  1. Coca Cola
  2. Sprite
  3. Fanta

Select drink: 2

Sample Output:
$10 note: 0
$5 note: 0
$2 coin: 0
$1 coin: 0
50c coin: 0
20c coin: 2
10c coin: 0
5c coin: 0

I can’t figure out how to write the code to display the change correctly, I’ve spent ages googling and I still can’t figure it out!!

def vending_machine
drinks = ["Coca Cola", "Sprite", "Fanta"]
cost = 1.60
payment = 0

puts "Cost per drink = $#{cost}"
  while payment < cost
      print "Please enter note or coin (0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10 or 20): "
      payment = gets.chomp.to_i
  end

puts "Make your selection:\n1. Coca Cola\n2. Sprite\n3. Fanta" 
selection = gets.chomp.to_i
  case selection
      when 1
        puts "Your #{drinks[0]} has been dispensed." 
      when 2
        puts "Your #{drinks[1]} has been dispensed." 
      else
        puts "Your #{drinks[2]} has been dispensed." 
    end

if payment > cost
  change = payment - cost
  puts "Your change is #{change.to_f}"
  puts "  $10 note: #{change.to_i / 10}
  $5 note: #{change.to_i / 5}
  $2 coin: #{change.to_i / 2}
  $1 coin: #{change.to_i / 1}
  50c coin: #{change.to_i / 0.50}
  20c coin: #{change.to_i / 0.20}
  10c coin: #{change.to_i / 0.10}
  5c coin: #{change.to_i / 0.05}" 
else
  puts "Have a great day!"
end

end

May be out in left field… First thing I would do is convert everything to cents.

10.00 * 100  =>  1000
-1.60 * 100  =>  -160
======================
                  840  Credit

That gives us a number to reduce. Next closest value to 1000 is 500…

                  840
-5.00 * 100  =>  -500    OD
======================
                  340

Next closest value to 500 is 200…

                  340
-2.00 * 100  =>  -200    OD
======================
                  140

Next closest value to 200 is 100

                  140
-1.00 * 100  =>  -100    OD
======================
                   40

Next closest value to 40 is 20

                   40
-0.20 * 100  =>   -20    OD
======================
                   20
                  -20    OD  (out of drawer)
======================
                    0

Now count back up the stack…

2 x 20c, 1 x 1.00, 1 x 2.00, 1 x 5.00  =>  8.40

1.60 from ten: $1.80, $2.00, $3, $5 and $10.

That’s how we were taught to give change when I was a kid and it stuck with me through fifty years of merchandising jobs at the till (groceries, restaurants, taverns, flea markets, &c).

2 Likes

Thank you, I’ll give this a go!!

1 Like