ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Price Decorators

Wrap a base price in discount, tax, shipping and coupon decorators applied in order.

สิ่งที่คุณจะได้เรียนรู้

  • Stack behaviours in layers around a value
  • Apply percentages in the right order
  • Clamp a value so it never goes below zero

โจทย์

ดูฉบับแปล

The decorator pattern adds behaviour by wrapping an object in layers. Each layer here changes the price of the layer inside it.

Start from base_price and apply the decorators in order:

  • discount p: reduce the price by p percent.
  • tax p: increase the price by p percent.
  • shipping a: add a fixed amount a.
  • coupon a: subtract a, but never go below 0.

Implement price_decorators(base_price, decorators).

Input

base_price: The starting price.

decorators: The layers, in the order they wrap the price. Amounts may have decimals.

Output

Return the final price. Answers within 1e-6 are accepted.

เงื่อนไข

0 ≤ base_price ≤ 1,000,000

0 ≤ number of decorators ≤ 100; 0 ≤ p ≤ 100, 0 ≤ a ≤ 100,000

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
base_price = 100
decorators = ["discount 10", "tax 8", "shipping 5"]

ผลลัพธ์ที่คาดหวัง:
expected = 102.2
อินพุต:
long long base_price = 100;
std::vector<std::string> decorators = {"discount 10", "tax 8", "shipping 5"};

ผลลัพธ์ที่คาดหวัง:
double expected = 102.2;
อินพุต:
long base_price = 100;
string[] decorators = new string[] {"discount 10", "tax 8", "shipping 5"};

ผลลัพธ์ที่คาดหวัง:
double expected = 102.2;

คำอธิบาย

100 − 10% = 90, plus 8% tax = 97.2, plus 5 shipping = 102.2.

ตัวอย่างที่ 2
อินพุต:
base_price = 20
decorators = ["coupon 25", "shipping 4"]

ผลลัพธ์ที่คาดหวัง:
expected = 4.0
อินพุต:
long long base_price = 20;
std::vector<std::string> decorators = {"coupon 25", "shipping 4"};

ผลลัพธ์ที่คาดหวัง:
double expected = 4.0;
อินพุต:
long base_price = 20;
string[] decorators = new string[] {"coupon 25", "shipping 4"};

ผลลัพธ์ที่คาดหวัง:
double expected = 4.0;

คำอธิบาย

The coupon would take the price below zero, so it stops at 0; shipping then makes it 4.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Apply the layers strictly in the given order.

คำใบ้ 2

Percentages are taken from the current price, not the base price.

คำใบ้ 3

A coupon can never push the price below 0.

ความซับซ้อนที่คาดหวัง

O(number of decorators) time, O(1) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก