C++ 中每 N 個訂單應用折扣


假設超市正在進行促銷活動,每到第 n 位顧客就會享受折扣。考慮超市中有一些產品,其中第 i 個產品的 ID 為 products[i],該產品的單價為 prices[i]。系統將計算顧客數量,當第 n 位顧客到達時,他/她將享受賬單折扣。然後系統將重新開始計算顧客數量。顧客訂購了每種產品的特定數量,其中 product[i] 是顧客訂購的第 i 個產品的 ID,amount[i] 是顧客訂購的該產品的數量。所以我們必須實現這個系統。Cashier 類將具有以下方法

  • Cashier(int n, int discount, int[] products, int[] prices) 此建構函式用於使用 n、折扣、產品及其價格初始化物件。

  • double getBill(int[] product, int[] amount) 這將返回賬單的值,並在需要時應用折扣。實際值的 10^-5 以內的答案將被接受為正確。

例如,使用 Cashier(3, 50, [1,2,3,4,5,6,7], [100,200,300,400,300,200,100]) 初始化 Cashier,現在呼叫 getBill 方法 -

getBill([1,2],[1,2]), getBill([3,7],[10,10]), getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]), getBill([4],[10]), getBill([7,3],[10,10]), getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]), getBill([2,3,5],[5,3,2]), then the outputs will be [500.0, 4000.0, 800.0, 4000.0, 4000.0, 7350.0, 2500.0]

為了解決這個問題,我們將遵循以下步驟 -

  • 定義一個名為 order 的對映

  • Cashier 的工作原理如下 -

  • curr := 0

  • 對於 i 的範圍為 0 到 prices 陣列的大小

    • order[produce[i]] := prices[i]

  • 設定折扣為給定的折扣率

  • getBill 方法的工作原理如下 -

  • 將 curr 增加 1,設定 flag := true,如果 curr = n,否則為 false

  • 如果 curr = n,則設定 curr := 0

  • ret := 0

  • 對於 i 的範圍為 0 到 product 陣列的大小 - 1

    • x := pro[i]

    • cost := order[x]

    • y :=amount[i]

    • 將 ret 增加 cost * y

  • 如果設定了 flag,則 ret := ret – (ret * discount) / 100

  • 返回 ret

示例(C++)

讓我們看看以下實現以獲得更好的理解 -

 即時演示

#include <bits/stdc++.h>
using namespace std;
class Cashier {
public:
   int curr;
   map <double, double> order;
   int n;
   int discount;
   Cashier(int n, int discount, vector<int>& pro, vector<int>& p) {
      curr = 0;
      for(int i = 0; i < p.size(); i++){
         order[pro[i]] = p[i];
      }
      this->n = n;
      this->discount = discount;
   }
   double getBill(vector<int> pro, vector<int> am) {
      curr++;
      bool flag = curr == n;
      if(curr == n){
         curr = 0;
      }
      double ret = 0;
      for(int i = 0; i < pro.size(); i++){
         double x = pro[i];
         double cost = order[x];
         double y = am[i];
         ret += (cost * y);
      }
      if(flag) ret = ret - (ret * discount) / 100;
      return ret;
   }
};
main(){
   vector<int> v1 = {1,2,3,4,5,6,7}, v2 =
   {100,200,300,400,300,200,100};
   Cashier ob(3, 50, v1, v2);
   v1 = {1,2}, v2 = {1,2};
   cout << (ob.getBill(v1, v2)) << endl;
   v1 = {3,7}, v2 = {10,10};
   cout << (ob.getBill(v1, v2)) << endl;
   v1 = {1,2,3,4,5,6,7}, v2 = {1,1,1,1,1,1,1};
   cout << (ob.getBill(v1, v2)) << endl;
   v1 = {4}, v2 = {10};
   cout << (ob.getBill(v1, v2)) << endl;
   v1 = {7,3}, v2 = {10,10};
   cout << (ob.getBill(v1, v2)) << endl;
   v1 = {7,5,3,1,6,4,2}, v2 = {10,10,10,9,9,9,7};
   cout << (ob.getBill(v1, v2)) << endl;
   v1 = {2,3,5}, v2 = {5,2,3};
   cout << (ob.getBill(v1, v2)) << endl;
}

輸入

See the main function

輸出

500
4000
800
4000
4000
7350
2500

更新於: 2020-04-29

254 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.