Start learning free

LESSON 621 OF 642 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Product Price in Rust

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:

  • The function new(name, price) in impl Product returns a new product. Its discount starts at 0.
  • get_price() returns the price.
  • set_price(value) sets the price. A negative value changes nothing, so the old price stays.
  • get_discount() returns the discount.
  • set_discount(value) sets the discount. Below 0 it becomes 0. Above 100 it becomes 100.
  • final_price() returns the price with the discount taken off. It rounds down to a whole cent.

Keep price and discount private. The name is a pub field. The setters take &mut self.

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 = Product::new("Pen", 250)
    p.get_price()
    p.set_discount(10)
    p.final_price()
    p.set_price(-40)
    p.get_price()
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 = Product::new("Lamp", 999)
    p.set_discount(150)
    p.get_discount()
    p.final_price()
    p.set_discount(-20)
    p.get_discount()
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 = Product::new("Mug", 999)
    p.set_discount(15)
    p.final_price()
    p.set_price(0)
    p.final_price()
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 Rust

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