Solved

# Algorithm for combination generator

Posted on 2008-06-12
7,434 Views
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
Question by:tejs1dhu
• 2

LVL 53

Expert Comment

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

LVL 1

Author Comment

Hi Infinity08

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

LVL 53

Accepted Solution

Infinity08 earned 250 total points
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

## Featured Post

Suppose you use Uber application as a rider and you request a ride to go from one place to another. Your driver just arrived at the parking lot of your place. The only thing you know about the ride is the license plate number. How do you find your U…
Linear search (searching each index in an array one by one) works almost everywhere but it is not optimal in many cases. Let's assume, we have a book which has 42949672960 pages. We also have a table of contents. Now we want to read the content on p…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…