Vending Machine

For this question, we ask you to design a vending machine. We divide this question into three parts, so you can complete them in order.

Part One

For the first part, you must design a Machine class representing the vending machine. Your system must support these following commands:

  • new_product <name> <price>: Creates a new product object with name which is a string, and price which is a non-negative integer.
  • print_products: Prints all products, each product in a line in format <name> <price>, sorted by price from lowest to highest.
  • insert_coin <value>: Adds money to internal state.
  • purchase <name>: Checks if the user inserted enough money and returns a boolean.
  • checkout: Prints the money left by the previous user, and clears internal state for the next user.

You may implement these however you like. However, preferably this should be easily expandable to accommodate new requirements.

Example

Input:

1instructions = [
2  ["new_product", "apple", "4"],
3  ["insert_coin", "5"],
4  ["purchase", "apple"],
5  ["purchase", "apple"],
6  ["checkout"],
7]

Output:

1[
2  "true",
3  "false",
4  "1"
5]

Try it yourself

Solution

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ