I am writing some code to transform an array of decimals so that they are discounted over time.
I initially wrote the following code:
private decimal[] deflateArray(decimal[] items, decimal deflateRate)
{
decimal[] deflatedItems = new decimal[items.Count()];
decimal factorAdjustment = 1;
for (int i = 0; i < items.Length; i++)
{
deflatedItems[i] = items[i] / factorAdjustment;
factorAdjustment = factorAdjustment * (1 + deflateRate);
}
return deflatedItems;
}
Then I realised that instead of having the factorAdjustment
variable, I can just use to the power of:
private decimal[] deflateArray(decimal[] items, decimal deflateRate)
{
decimal[] deflatedItems = new decimal[items.Count()];
for (int i = 0; i < items.Length; i++)
{
deflatedItems[i] = items[i] / (decimal)Math.Pow((double)(1 + deflateRate), i);
}
return deflatedItems;
}
As Math.Pow()
only accepts and returns double
s, I think it's easier to create a wrapper function for it:
private decimal PowerOf(decimal x, decimal y)
{
return (decimal)Math.Pow((double)x, (double)y);
}
and then simplify:
private decimal[] deflateArray(decimal[] items, decimal deflateRate)
{
decimal[] deflatedItems = new decimal[items.Count()];
for (int i = 0; i < items.Length; i++)
{
deflatedItems[i] = items[i] / PowerOf(1 + deflateRate, i);
}
return deflatedItems;
}
Then I realised that I really just want to transform the array and don't need a second array:
private void deflateArray(decimal[] items, decimal deflateRate)
{
for (int i = 0; i < items.Length; i++)
{
items[i] = items[i] / PowerOf(1 + deflateRate, i);
}
}
and then I can simplify this to:
private void deflateArray(decimal[] items, decimal deflateRate)
{
for (int i = 0; i < items.Length; i++)
{
items[i] /= PowerOf(1 + deflateRate, i);
}
}
so my final version is:
private void deflateArray(decimal[] items, decimal deflateRate)
{
for (int i = 0; i < items.Length; i++)
{
items[i] /= PowerOf(1 + deflateRate, i);
}
}
private decimal PowerOf(decimal x, decimal y)
{
return (decimal)Math.Pow((double)x, (double)y);
}
I'm sure it can probably done in a one-liner by someone who is cleverer than me. Which version is the most easily understood?
I am not really worried about the performance as the array of items will only ever have 100 or 200 items and it's never done in a loop.
PowerOf(1m + deflateRate, i)
where i == 0. This gives a divisor of 1. \$\endgroup\$ – AlanT Apr 28 '17 at 8:48