I want to get a list of all possible combinations with repetion.
e.g.
Input: 1,2,3
Result: 111,112,...,332,333
for this i use this modified method which is working fine
public static IEnumerable<IEnumerable<T>> CombinationsWithRepeat<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } : elements.SelectMany((e, i) => elements.CombinationsWithRepeat(k - 1).Select(c => (new[] { e }).Concat(c)));
}
my problem is the memory usage of this recursive approach. With a input of 60 elements and K = 4 there is already a Out Of Memory Exception
.
I need to run this with K = 10.
Question: Is there a easy way to avoid this exception? Do i need a iterative approach?
Update:
referring to Corak's comment - K has to be dynamic
this should work with 60 Elements and K = 10
but it's not dynamic.
StreamWriter sr = new StreamWriter(@"c:\temp.dat");
List<char> cList = new List<char>() { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
for (int i = 0; i < cList.Count; i++)
for (int j = 0; j < cList.Count; j++)
for (int k = 0; k < cList.Count; k++)
sr.WriteLine(cList[i] + cList[j] + cList[k]);