I have a function that generates a cartesian product for me
var abcArray = new string[] { "a", "b", "c" };
var xyzArray = new string[] { "1", "2", "3" };
var combos = CartesianProductSmart(abcArray, xyzArray);
private static string[][] CartesianProductSmart(string[] arr1, string[] arr2)
{
return arr1.SelectMany(s1 => arr2, (s1, s2) => new string[] { s1, s2 })
.ToArray();
}
My output looks like:
a,1
a,2
a,3
b,1
b,2
b,3
c,1
c,2
c,3
How can I transform this function into something more complex, like forming multidimensional arrays:
array3 = [ {"A1", "B2", "C3"},
{"A1", "B3", "C2"},
{"A2", "B1", "C3"},
{"A2", "B3", "C1"},
{"A3", "B2", "C1"},
{"A3", "B1", "C2"}
]
What I want is the cartesian product just using every element of both arrays and form that into an array. (I'm aware that the array sizes will differ based on inputs). My idea so far is to do the cartesian product, assign the first element as the first cartesian product result and then iterate over the rest of the cartesian products and add into a new array by checking if there's no duplicates, then selecting only unique members, but that seems highly inefficient.
My advise would be, if you are using complex structures, you should not use standard structures anymore, but create classes that represent the data that you model and the operations that you can perform on these objects.
Apparently your program has the notion of
Matrix
(not sure if you use the same term in English mathematics)A Matrix of M by N has M columns, and N rows.
I'm not sure if it is wise to put your
abcarray
in a matrix of 3 by 1, or that you want to put that in a special class that you would call a Vector. Maybe a Vector is a derived class of matrix of N by 1? or 1 by N?Anyway, apparently you can do an operation on two Vectors:
Usage would be:
Well this looks neat enough to me, so let's continue on this path.
A Vector has a
Dimension
. When creating a Vector object, you have to specify theDimension
. During lifetime of the Vector you can't change itsDimension
.A Vector has
Coordinates
, numbered from 0 toDimension-1
. You can get and set a specific Coordinate. For simplicity we use the index to access the Coordinates.Operations that you can do on a Vector: Add / Subtract / Negate / Multiply / ... This is a bit out of scope of your question so I won't go in to this.
Implementation of IReadOnlyCollection is fairly straightforward:
For initializations the following extension methods would be nice. If you are not familiar with extension methods, read extension methods demystified
Usage:
I design a Matrix as a non-changeable two dimensional array.
Of course, if you really want to interpret a Matrix as a two dimensional array:
Finally the cartesian product of two vectors, returning a Matrix. The problem is, that we need a function to "combine" one x-coordinate with one "y" coordinate. With a vector of numbers this could be a multiplication, with a vector of strings you want to use concatenation.