jslice - 1 year ago 69

C++ Question

Part of a program that I'm working on implements a function that takes in the package weight as an argument and calculates the shipping cost based on that weight. The criteria for the cost/lb is as follows:

`Package Weight Cost`

-------------- ----

25 lbs & under $5.00 (flat rate)

26 - 50 lbs above rate + 0.10/lb over 25

50 + lbs above rate + 0.07/lb over 50

I used an if-if else-if to make the calculations, but feel like its a bit repetitive:

`const int TIER_2_WEIGHT = 25;`

const int TIER_3_WEIGHT = 50;

const float TIER_1_RATE = 5.00;

const float TIER_2_RATE = 0.10;

const float TIER_3_RATE = 0.07;

float shipPriceF;

if(shipWeightF <= TIER_2_WEIGHT)

{

shipPriceF = TIER_1_RATE;

}

else if(shipWeightF <= TIER_3_WEIGHT)

{

shipPriceF = ((shipWeightF - TIER_2_WEIGHT) * TIER_2_RATE) +

TIER_1_RATE;

}

else

{

shipPriceF = ((shipWeightF - TIER_3_WEIGHT) * TIER_3_RATE) +

((TIER_3_WEIGHT - TIER_2_WEIGHT) * TIER_2_RATE) +

TIER_1_RATE;

}

return shipPriceF;

So, the question is... is this the best way to accomplish this task, or should I be looking for a different solution?

Answer Source

First at all, you code looks clear and ok as it is.

Of course, you could deduplicate the redundant parts of the formulas by using a cumulative approach:

```
float shipPriceF = TIER_1_RATE; // to be paid anyway
if (shipWeightF > TIER_2_WEIGHT) // add the tier 2 if necessary
{
shipPriceF += (min(shipWeightF, TIER_3_WEIGHT) - TIER_2_WEIGHT) * TIER_2_RATE;
}
if(shipWeightF > TIER_3_WEIGHT) // add the tier 3 if really necessary
{
shipPriceF += (shipWeightF - TIER_3_WEIGHT) * TIER_3_RATE);
}
```

Well, this could even be simplified further:

```
float shipPriceF = TIER_1_RATE
+ max(min(shipWeightF,TIER_3_WEIGHT)-TIER_2_WEIGHT,0) * TIER_2_RATE
+ max(shipWeightF-TIER_3_WEIGHT,0) * TIER_3_RATE;
```

For 3 scales, it's probably ok with this synthetic formula. If you want more flexibility however, you could think of iterating throug a vector of rates instead of using constants. This would allow for a variable number of scales. If you're sure that the formula is always progressive (eg. "above + new unit price for what's exceding") use then the cumulative approach.