Robert Bravery said:
WEll I want to eventual extract the data and save it to a table.
I used two arrays as an example, but infact I don't know how many array sets
there can be, up to a maximum of 5, so there could be any number from one
to five sets. Then each array set can have any number of elements in that
array
The point is I don't know how many sets there will be , to a mx of five, and
I don't know how many elements there will be in each set
so I could also have the following, I dont know:
{'apple','orange','banana'},{'man','woman','child'},{'red','green','blue','w
hite','black'}
which should produce a cross product like:
Okay. Here's a sample which takes as many string arrays as you like. It
uses recursion, which wouldn't be a good idea if you wanted a cross-
product of very deep arrays, but then that quickly becomes infeasible
anyway.
You'll want to consider how you want to process the table - you could
fairly easily write an iterator which returns a string array on each
iteration, especially with C# 2.0 iterators.
using System;
using System.Text;
public class Test
{
static void Main()
{
string[] first = {"one", "two", "three"};
string[] second = {"red", "green", "blue"};
PrintCrossProduct(new string[]{"apple","orange","banana"},
new string[]{"man","woman","child"},
new string[]{"red","green","blue",
"white","black"});
}
static void PrintCrossProduct(params string[][] arrays)
{
PrintCrossProduct(arrays, 0, new string[arrays.Length]);
}
static void PrintCrossProduct(string[][] arrays,
int depth, string[] current)
{
for (int i=0; i < arrays[depth].Length; i++)
{
current[depth] = arrays[depth]
;
if (depth < arrays.Length-1)
{
PrintCrossProduct(arrays, depth+1, current);
}
else
{
StringBuilder builder = new StringBuilder();
foreach (string x in current)
{
builder.Append(x);
builder.Append(" ");
}
// Remove the extraneous trailing space
// (This will fail if there are no arrays, but you can
// guard against that if you need to)
builder.Length--;
Console.WriteLine (builder);
}
}
}
}