I want to calculate all possible (using a certain step) distributions of a number of items. The sum has to add up to 1. My first approach was the following:
var percentages = new List<double>(new double[3]);
while (Math.Abs(percentages.Last() - 1.0) > 0.01)
{
Increment(percentages, 0);
if (Math.Abs(percentages.Sum() - 1.0) < 0.01)
{
percentages.ForEach(x => Console.Write("{0}\t", x));
Console.WriteLine();
}
}
private void Increment(List<double> list, int i)
{
if (list.Count > i)
{
list[i] += 0.1;
if (list[i] >= 1)
{
list[i] = 0;
Increment(list, ++i);
}
}
}
Which outputs the wanted results:
1 0 0
0.9 0.1 0
0.8 0.2 0
0.7 0.3 0
0.6 0.4 0
0.5 0.5 0
0.4 0.6 0
0.3 0.7 0
0.2 0.8 0
0.1 0.9 0
0 1 0
0.9 0 0.1
..
I'm wondering how to speed up the calculation, as the number of items can become very large (>20). Obviously I calculate a lot of distributions just to throw them away because they don't add up to 1. Any ideas?