問題
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
例
入力:
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.
入力:
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 つずつ開いてみましょう。
ヒント 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用に調整されています。上記の説明と制約に従ってください。