# Ordered Unique Combinations [closed]

You could use a nested for loop:

``````for (int i = 0; i < courses[0].Length; i++)
{
for (int j = 0; j < courses[1].Length; i++)
{
for (int k = 0; k < courses[2].Length; i++)
{
//Do whatever you need with the combo, accessed like:
//courses[0][i], courses[1][j], courses[2][k]
}
}
}
``````

Of course, this solution gets really messy the more nesting you need. If you need to go any deeper, I would use some kind of recursive function to traverse the collection and generate the combinations.

It would be something like:

``````class CombinationHelper
{
public List<List<Course>> GetAllCombinations(Course[][] courses)
{
return GetCourseCombination(courses, 0);
}

public List<List<Course>> GetCourseCombination(Course[][] courses, int myIndex)
{
List<List<Course>> combos = new List<List<Course>>();

for (int i = 0; i < courses[myIndex].Length; i++)
{
if (myIndex + 1 < courses.GetLength(0))
{
foreach (List<Course> combo in GetCourseCombination(courses, myIndex + 1))
{
}
}
else
{
List<Course> newCombination = new List<Course>() { courses[myIndex][i] };
}
}
return combos;
}
}
``````

I tested this (substituting “int” for “Course” to make verification easier) and it produced all 8 combinations (though not in order, recursion tends to do that. If I come up with the ordering code, I’ll post, but it shouldn’t be too difficult).

Recursive functions are hard enough for me to come up with, so my explanation won’t be very good. Basically, we start by kicking the whole thing off with the “0” index (so that we start from the beginning). Then we iterate over the current array. If we aren’t the last array in the “master” array, we recurse into the next sub-array. Otherwise, we create a new combination, add ourselves to it, and return.

As the recursive stack “unwinds” we add the generated combinations to our return list, add ourselves to it, and return again. Eventually the whole thing “unwinds” and you are left with one list of all the combinations.

Again, I’m sure that was a very confusing explanation, but recursive algorithms are (at least for me) inherently confusing. I would be happy to attempt to elaborate on any point you would like.