Problem overview
You write a VendingMachine class for a machine that sells one kind of item at a fixed price of 150. The machine remembers the money inserted so far, its credit, and offers three actions:
void insert(double amount)adds money to the credit. It prints and returns nothing.string select()tries to buy one item. With too little credit it returns"Need N more", where N is the missing amount as a whole number, and leaves the credit alone. Otherwise it subtracts the price from the credit and returns"Dispensing!". Exact payment works, and any extra money stays in the credit.double refund()returns the whole credit and sets it back to 0, so asking again returns 0.
The code at the bottom of the starter runs three purchases. Inserting 50 is short by 100, so the machine answers Need 100 more. Inserting 150 more makes the credit 200, so it dispenses and keeps 50 (200 - 150), and the refund is 50. Next, 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100 and the refund is 100:
Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100
Approach: state plus methods that change it
A class is a good fit here because the machine has memory. Each VendingMachine keeps its own credit between calls, and the methods read and update it. The two fields are private, double credit = 0; and double price = 150;, so only the machine's own methods can change them. Their default values are written where they are declared, so a plain VendingMachine m; already starts with no money and a price of 150, and no constructor is needed.
The key design point is when the credit changes. select has two outcomes and only one of them spends money:
- When the credit is too low,
selectonly reports the shortfall. The customer may insert more and try again, so nothing is subtracted. - When the credit is enough,
selectsubtracts the price. If you forget this, the leftover credit is wrong and the refund gives back too much.
refund has a different trap. It must return the old credit and also reset it to 0. After credit = 0 the old value is gone, so refund saves it in a local variable first.
Step by step
- Declare
VendingMachineand write its closing};right away. - Open the
private:part. The credit and the price are the machine's own business. - Add
double credit = 0;: a new machine holds no money. - Add
double price = 150;: every item costs 150. - Open the
public:part so the code outside can call the methods. - Start
insertas avoidmethod taking adoublenamedamount. - Add the amount to
creditwith+=. It adds to what is already there; it doesn't replace it. - Start
selectas a method with no parameters that returns astring. - Handle too little money. If
credit < price, return the message built from the missing amount. The amount is cast toint, thento_stringturns it into text that can join the message. - Charge the price below that
if:credit -= price;. This line is reached only when the credit covers the price. - Return
"Dispensing!". - Start
refundas a method with no parameters that returns adouble. - Save the credit in a
doublenamedr. - Reset
creditto 0. - Return
r, the saved money. Returningcredithere would return 0.
The solution in C++
class VendingMachine {
private:
double credit = 0;
double price = 150;
public:
void insert(double amount) {
credit += amount;
}
string select() {
if (credit < price) return "Need " + to_string((int)(price - credit)) + " more";
credit -= price;
return "Dispensing!";
}
double refund() {
double r = credit;
credit = 0;
return r;
}
};
class Solution {
public:
void mainFunction() {
VendingMachine m;
m.insert(50);
cout << m.select() << endl;
m.insert(150);
cout << m.select() << endl;
cout << "Refunded: " << m.refund() << endl;
m.insert(150);
cout << m.select() << endl;
cout << "Refunded: " << m.refund() << endl;
m.insert(100);
cout << m.select() << endl;
cout << "Refunded: " << m.refund() << endl;
}
};
C++ details worth knowing
- Default member initialisers.
double credit = 0;inside the class gives every new object that starting value. This is whyVendingMachine m;works without a constructor. - Why cast to
int.to_stringon adoubleprints six decimals. With a price of 150 and a credit of 50.5,to_string(price - credit)gives99.500000, whileto_string((int)(price - credit))gives99. The cast truncates toward zero, so a fractional shortfall is cut down, not rounded. With the whole-number amounts of this lesson the result is exact. - Building a message.
"Need " + to_string(...) + " more"works becauseto_stringreturns astd::string, and adding a string to a string literal is allowed. Two literals can't be added directly:"Need " + " more"doesn't compile. - Doubles for money. Whole numbers such as 50, 150 and 200 are represented exactly in a
double, so the comparisoncredit < priceis reliable here. With fractional amounts, tiny representation errors can matter.
Complexity
Every method does a fixed amount of work: a comparison, an addition or a subtraction, so each call is O(1) in time and the machine uses O(1) space for its two numbers.
Edge cases and common mistakes
- Using
<=instead of<. Exact payment must work. Withcredit <= price, inserting exactly 150 would be refused. - Subtracting before checking. The credit must stay unchanged when the answer is
Need N more. - Forgetting
credit -= price;. The refund after a purchase would return the whole amount that was inserted. In the driver it would print 200 instead of 50. - Returning
creditafter resetting it. The refund would always be 0. Return the saved variable. - Replacing instead of adding.
credit = amount;ininsertloses money that was already inserted.
Key takeaways
- Private fields with default values hold the machine's state between calls.
- Change the state only on the branch that should change it: only a successful
selectcharges the price. - Save a value in a local variable before resetting it when you also need to return it.
