Start learning free

LESSON 618 OF 639 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Product Price in Go

Practice O(1)

Build a Product struct for a shop. A product has a name, a price and a discount.

The price is in cents, and it can never go below 0. The discount is a percent from 0 to 100. The setters keep both rules.

Implement the struct Product:

  • NewProduct(name, price) returns a new product. Its discount starts at 0.
  • getPrice() returns the price.
  • setPrice(value) sets the price. A negative value changes nothing, so the old price stays.
  • getDiscount() returns the discount.
  • setDiscount(value) sets the discount. Below 0 it becomes 0. Above 100 it becomes 100.
  • finalPrice() returns the price with the discount taken off. It rounds down to a whole cent.

Keep price and discount unexported. The name is the exported field Name. The setters have a pointer receiver.

Each test case makes one product. Then it runs a list of operations on it, in order.

The output has one line per test case. It shows the name and a colon. Then it lists what each read gives, separated by spaces.

 

Example 1:

Input:
    p := NewProduct("Pen", 250)
    p.getPrice()
    p.setDiscount(10)
    p.finalPrice()
    p.setPrice(-40)
    p.getPrice()
Output: Pen: 250 225 250
Explanation: 10% of 250 cents is 25 cents, so the pen costs 225.
The price can't be -40, so it stays 250.

Example 2:

Input:
    p := NewProduct("Lamp", 999)
    p.setDiscount(150)
    p.getDiscount()
    p.finalPrice()
    p.setDiscount(-20)
    p.getDiscount()
Output: Lamp: 100 0 0
Explanation: 150 is above 100, so the discount becomes 100.
With 100% off, the lamp costs 0.
Then -20 is below 0, so the discount becomes 0.

Example 3:

Input:
    p := NewProduct("Mug", 999)
    p.setDiscount(15)
    p.finalPrice()
    p.setPrice(0)
    p.finalPrice()
Output: Mug: 849 0
Explanation: 15% off 999 cents leaves 849.15 cents.
Rounded down, that is 849.
A price of 0 is allowed. It stays 0 after any discount.

 

Constraints:

  • The first price is a whole number from 0 to 10,000,000.
  • A new price is from -10,000,000 to 10,000,000.
  • A new discount is from -1,000 to 1,000.
  • A name is one word of letters.
  • 1 to 1,000 operations per test case.
  • Each test case reads at least one value.
STEP 1 OF 10
    Ctrl + Enter to check

    Product Price in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free