I have a need to create a list of combinations of numbers. The numbers are quite small so I can use byte rather than int. However it requires many
What you are doing is counting (with variable radix, but still counting).
Since you are using C#, I assume you don't want to play with useful memory layout and data structures that let you really optimize your code.
So here I'm posting something different, which may not suit your case, but it's worth noting: In case you actually access the list in a sparse fashion, here a class that let you compute the i-th element in linear time (rather than exponential as the other answers)
class Counter
{
public int[] Radices;
public int[] this[int n]
{
get
{
int[] v = new int[Radices.Length];
int i = Radices.Length - 1;
while (n != 0 && i >= 0)
{
//Hope C# has an IL-opcode for div-and-reminder like x86 do
v[i] = n % Radices[i];
n /= Radices[i--];
}
return v;
}
}
}
You can use this class this way
Counter c = new Counter();
c.Radices = new int[] { 2,3,4,3,4,3,3,4,2,4,4,3,4};
now c[i] is the same as your list, name it l, l[i].
As you can see, you can easily avoid all those loops :) even when you pre compute all the list at whole since you can simply implement a Carry-Ripple counter.
Counters are a very studied subject, I strongly advice to search for some literature if you feel.