x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 7484

# Algorithm for combination generator

Hi

I'm wondering if you could give me a hand with an algorithm.

I need to write a algorithm for generating combinations from n number of sets (of integers).

I can write code that will take my fixed number of sets and produce the combinations but Im lost on how I would be able to do this for n number of sets.

I've attached code for generating combinations from a fixed number of sets.

Will appreciate anyones help or guidance.

Thanks
``````int[] firstSet = new int[] { 1, 2, 3, 4, 5 };
int[] secondSet = new int[] { 6, 7, 8, 9, 10, 11 };
int[] thirdSet = new int[] { 12, 13, 14 };
int[] fourthSet = new int[] { 15, 16, 17, 18 };
int counter = 0;

foreach (int firstSetVariable in firstSet)
{
foreach (int secondSetVariable in secondSet)
{
foreach (int thirdSetVariable in thirdSet)
{
foreach (int fourthSetVariable in fourthSet)
{
Response.Write(counter + ": " + firstSetVariable + "," + secondSetVariable + "," + thirdSetVariable + "," + fourthSetVariable + "<br />");
counter += 1;
}
}
}
}
``````
0
tejs1dhu
• 2
1 Solution

Commented:
If n isn't too big, you could make the algorithm recursive ...
0

Author Commented:
Hi Infinity08

Making this recursive is the aim, however I am not sure how to implement this using C#.  Any ideas?
0

Commented:
In pseudo code it could look something like this :

function(n, sets, combination)
if n is max then print combination
else
for every element in the n-th set from sets
set the n-th value in the combination to that element
call function(n + 1, sets, combination)
end for
end else
end function
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.