470,843 Members | 1,992 Online

# All Possible Combinations of Multiple Lists

I have multiple ArrayLists, could be 2 or 3 or 10 lists, with multiple
values in them. Now what I need to do is to get a combination of all
of them.

For example, if I have 3 lists with the following values:

List 1: 3, 5, 7
List 2: 3, 5, 6
List 3: 2, 9

I would get these combinations

3, 3, 2
3, 3 , 9
3, 5, 2
3, 5, 9
3, 6, 2
3, 6, 9
5, 3, 2
5, 3, 9
5, 5, 2
5, 5, 9
5, 6, 2
5, 6, 9

etc etc....

Now the problem is I cannot do this easily because I do not know how
many lists I have, therefore determine how many loops I need.

Sep 11 '07 #1
3 11793
I forgot to say that I these arraylists are all stored in a list,
therefore I know the count of arraylists I have.

Sep 11 '07 #2
DarkSoul wrote:
I have multiple ArrayLists, could be 2 or 3 or 10 lists, with multiple
values in them. Now what I need to do is to get a combination of all
of them.

For example, if I have 3 lists with the following values:

List 1: 3, 5, 7
List 2: 3, 5, 6
List 3: 2, 9

I would get these combinations

3, 3, 2
3, 3 , 9
3, 5, 2
....
Now the problem is I cannot do this easily because I do not know how
many lists I have, therefore determine how many loops I need.
As you have already found then the solution is recursion.

Below are another coding solution.

Arne

====================================

using System;
using System.Collections.Generic;

namespace E
{
public class Permuting<T>
{
public delegate void Processor(T[] a);
private static void Permute(T[] res, int ix, List<List<T>data,
Processor p)
{
foreach(T v in data[ix])
{
res[ix] = v;
if(ix >= data.Count - 1)
{
p(res);
}
else
{
Permute(res, ix + 1, data, p);
}
}
}
public static void Permute(List<List<T>data, Processor p)
{
Permute(new T[data.Count], 0, data, p);
}
}
public class TestClass
{
public static void Print1(string[] a)
{
for(int i = 0; i < a.Length; i++)
{
Console.Write(a[i]);
}
Console.WriteLine();
}
public static void Print2(int[] a)
{
for(int i = 0; i < a.Length; i++)
{
if(i 0)
{
Console.Write(", ");
}
Console.Write(a[i]);
}
Console.WriteLine();
}
public static void Main(string[] args)
{
List<List<string>data1 = new List<List<string>>();
Permuting<string>.Permute(data1, Print1);
List<List<int>data2 = new List<List<int>>();
Permuting<int>.Permute(data2, Print2);