I have an algorithm to calculate the amount of products on target cost. The cost of one product is not constant, it is more expensive by 10%. The target cost may be exceeded if it is closer than the incomplete cost.
I need to optimize code and exclude loop, because it is not effective at high target cost.
This is my working solution with unit test (nunit framework)
public static int CalculateProductAmountOnCost( double targetCost, double productRate )
{
if ( targetCost <= 0 || productRate <= 0 )
return 1;
var previousCollectedCost = 0.0;
var collectedCost = 0.0;
var amount = 0;
for ( ; collectedCost < targetCost; amount++ )
{
previousCollectedCost = collectedCost;
collectedCost += productRate*Math.Pow( 1.1, amount );
}
if ( targetCost - previousCollectedCost < collectedCost - targetCost )
amount -= 1;
return Math.Max( 1, amount );
}
[Test]
[TestCase( 9, 2, 4 )]
[TestCase( 7, 2, 3 )]
[TestCase( 0, 2, 1 )]
[TestCase( 9, 0, 1 )]
[TestCase( 4.5, 0.2, 12 )]
public void TradeDealHelper_CalculateProductAmountOnGemCostTest( double targetCost, double productRate,
int expectedAmount )
{
var actualAmount = TradeDealHelper.CalculateProductAmountOnCost( targetCost, productRate );
Assert.AreEqual( expectedAmount, actualAmount );
}