Reputation: 95
I have this array of char: private char[] posibilities = { 'a', 'b', 'c' };
And I want all possible combination of them, then I made three nested for:
for (int cont = 0; cont < posibilities.Length; cont++)
{
for (int i = 0; i < posibilities.Length; i++)
{
for (int j = 0; j < posibilities.Length; j++)
{
listBox1.Items.Add(posibilities[cont].ToString() + posibilities[i].ToString() + posibilities[j].ToString());
}
}
}
My question is: How can I do something in case that I want to add more chars to my array without adding more fors to my nested for? Imagine if I have 20 chars on the array, I can't do 20 for....or that is the only way?
(By the way, I have been trying to solve this since 3 months ago, and still I can't)
Upvotes: 2
Views: 218
Reputation: 203802
public static IEnumerable<IEnumerable<T>> PermutationsWithRepitition<T>(IList<T> source)
{
return PermutationsWithRepitition(source, source.Count);
}
//private recursive method that does all of the work.
private static IEnumerable<IEnumerable<T>> PermutationsWithRepitition<T>(IList<T> source, int resultSize)
{
if (resultSize == 1)
return source.Select(item => new[] { item });
else
{
return PermutationsWithRepitition(source, resultSize - 1)
.SelectMany(permutation => source.Select(item => new[]{item}.Concat(permutation)));
}
}
example usage:
char[] posibilities = new[] { 'a', 'b', 'c' };
foreach (var permutation in PermutationsWithRepitition(posibilities))
{
Console.WriteLine(new string(permutation.ToArray()));
}
Upvotes: 0
Reputation: 3553
Try this recursive approach:
void RecursiveApproach(char[] possibilities, string cur)
{
if (cur.Length == c.Length)
{
listBox1.Items.Add(cur);
return;
}
for (int i = 0; i < possibilities.Length; i++)
{
RecursiveApproach(possibilities, cur + possibilities[i]);
}
}
// Usage
RecursiveApproach(possibilities, "");
listBox1 can be passed as third parameter to this function if it is impossible to make it global visible.
But be careful with large numbers, this list will grow VERY fast))
Upvotes: 1