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.Collecti ons.Generic;
namespace E
{
public class Permuting<T>
{
public delegate void Processor(T[] a);
private static void Permute(T[] res, int ix, List<List<T>dat a,
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<Li st<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.WriteLi ne();
}
public static void Print2(int[] a)
{
for(int i = 0; i < a.Length; i++)
{
if(i 0)
{
Console.Write(" , ");
}
Console.Write(a[i]);
}
Console.WriteLi ne();
}
public static void Main(string[] args)
{
List<List<strin g>data1 = new List<List<strin g>>();
data1.Add(new List<string>()) ;
data1.Add(new List<string>()) ;
data1.Add(new List<string>()) ;
data1.Add(new List<string>()) ;
data1[0].Add("A");
data1[0].Add("B");
data1[0].Add("C");
data1[0].Add("D");
data1[1].Add("X");
data1[1].Add("Y");
data1[1].Add("Z");
data1[2].Add("1");
data1[2].Add("2");
data1[3].Add("*");
data1[3].Add("#");
Permuting<strin g>.Permute(data 1, Print1);
List<List<int>d ata2 = new List<List<int>> ();
data2.Add(new List<int>());
data2.Add(new List<int>());
data2.Add(new List<int>());
data2[0].Add(3);
data2[0].Add(5);
data2[0].Add(7);
data2[1].Add(3);
data2[1].Add(5);
data2[1].Add(6);
data2[2].Add(2);
data2[2].Add(9);
Permuting<int>. Permute(data2, Print2);
Console.ReadKey ();
}
}
}