Home > OS >  How to calculate different discounts on range of products
How to calculate different discounts on range of products

Time:07-16

I have a structrue as below,

struct ProductDetails
{
    string name;
    double actualPrice;
    double finalPrice;
}product;

I have different products say, product name ={Apple, bag of Carrot, Orange, sale bag of beans, cake, sale bag of grapes,cookie}

so in these products,

fruits and vegies have 2% discount others has 4% discount. Product starts with 'sale' has extra 10% discount on top of its category(how to write generic code for one starts with 'sale').

//PART OF THE CODE
{
    std::vector<ProductDetails> itemsV;

    // some logic here and got all the ProductDetails

    itemsV.pushback(product);
    for(auto &item: itemsV)
    {
        if(item.name == ("Apple" || "bag of Carrot" || "Orange"))
        {
            item.finalPrice = discount(item.price,2,0);
        }
        else if(item.name == ("sale bag of beans" || "sale bag of grapes"))
        {
           item.finalPrice = discount(item.price,2,10);
        }
        else
        {
            item.finalPrice = discount(item.price,4,0);
        }
        // do something with the finalPrice.
    }
}

I would like to know any other better and efficient way to do the above job.

Below is the template of calculating the final price after discount with three different arguments. //original Price, discount percentage, additional discount.

double discount(double op, float dp=0.0, float additional=0.0)
        {
            // calculate discount and return final price
        }

CodePudding user response:

If I was you I would add an enum for the items you wish to group rather than string matches, and add this to your struct. Int compares are much less bug prone than string compares.

enum class FoodType{
    Vegetable,
    Fruit,
    BreakfastFood,
    etc
}

struct ProductDetails
{
    string name;
    double actualPrice;
    double finalPrice;
    FoodType type;
}product;

Then create a map between FoodType and discount

std::map<FoodType , double> discountMap;

Then you can apply a discount to the food type and apply it all at once. Soemthing like this, note not using a compiler just banging it out so you might need to fix-up a bit but it should be mostly right

for(auto &item: itemsV)
{
    auto it = discountMap.find(item.type);
    if (it != discountMap.end()){
        item.finalPrice = item.actualPrice * discountMap.at(item.type);
    }
}

Then just set your discounts and you're good to go.

discountMap[FoodType::Fruit] = 0.9; //90% of value or 10% discount

CodePudding user response:

if (item.name.find("sale") == 0) {
... 

This checks if the string starts with sale. See find

edit: I was assuming this is some school assignment in which the struct is not changeable. If you can add fields to the struct, the other answer is the way to go.

  •  Tags:  
  • c
  • Related