Given 2 arrays Array1 = {a,b,c...n}
and Array2 = {10,20,15....x}
how can I generate all possible combination as Strings a(i) b(j) c(k) n(p)
where
1 <= i <= 10, 1 <= j <= 20 , 1 <= k <= 15, .... 1 <= p <= x
Such as:
a1 b1 c1 .... n1
a1 b1 c1..... n2
......
......
a10 b20 c15 nx (last combination)
So in all total number of combination = product of elements of array2 =
(10 X 20 X 15 X ..X x)
Similar to a Cartesian product, in which the second array defines the upper limit for each element in first array.
Example with fixed numbers,
Array x = [a,b,c]
Array y = [3,2,4]
So we will have 3*2*4 = 24 combinations. Results should be:
a1 b1 c1
a1 b1 c2
a1 b1 c3
a1 b1 c4
a1 b2 c1
a1 b2 c2
a1 b2 c3
a1 b2 c4
a2 b1 c1
a2 b1 c2
a2 b1 c3
a2 b1 c4
a2 b2 c1
a2 b2 c2
a2 b2 c3
a2 b2 c4
a3 b1 c1
a3 b1 c2
a3 b1 c3
a3 b1 c4
a3 b2 c1
a3 b2 c2
a3 b2 c3
a3 b2 c4 (last)
I'm not willing to give you the complete source code. So here's the idea behind.
You can generate the elements the following way:
I assume
A=(a1, a2, ..., an)
andB=(b1, b2, ..., bn)
(soA
andB
each holdn
elements).Then do it recursively! Write a method that takes an
A
and aB
and does your stuff:If
A
andB
each contain just one element (calledan
resp.bn
), just iterate from 1 tobn
and concatenatean
to your iterating variable.If
A
andB
each contain more then one element, grab the first elements (a1
respb1
), iterate from 1 tobn
and do for each iteration step:A
andB
starting at the second element, i.e.A'=(a2, a3, ..., an)
respB'=(b2, b3, ..., bn)
. For every element generated by the recursive call, concatenatea1
, the iterating variable and the generated element from the recursive call.Here you can find an analouge example of how to generate things in C#, you "just" have to adapt it to your needs.
Fon another solution not linq based you can use:
You can find an example on how to use it here.
Fon another solution not linq based, more effective:
Alternative solution:
Step one: read my series of articles on how to generate all strings which match a context sensitive grammar:
http://blogs.msdn.com/b/ericlippert/archive/tags/grammars/
Step two: define a grammar that generates the language you want. For example, you could define the grammar:
Clearly you can easily generate that grammar definition string from your two arrays. Then feed that into the code which generates all strings in a given grammar, and you're done; you'll get all the possibilities. (Not necessesarily in the order you want them in, mind you.)