I have a list of arrays and I would like to generate all possible permutations and save the output in a 2D double matrix.
Let's assume the list of array is given by
List<double[]> myArray = new List<double[]>
{
new double[] { 1.2, 1.3, 1.4},
new double[] { 2.1, 2.2 },
new double[] { 3.1 }
};
The expected output is a 2D double array of size 6 x 3. 6 comes from the product of length all arrays in the list and 3 is the number of arrays in the list. The element of it has the form
{
{ 1.2, 2.1, 3.1 },
{ 1.2, 2.2, 3.1 },
{ 1.3, 2.1, 3.1 },
{ 1.3, 2.2, 3.1 },
{ 1.4, 2.1, 3.1 },
{ 1.4, 2.2, 3.1 }
}
I have tried the following piece of code
public static IEnumerable<IEnumerable<double>> Permutations2(List<double[]> array, int column)
{
if (column == array.Count)
{
yield return Enumerable.Empty<double>();
yield break;
};
for (int j = 0; j < array[column].GetLength(0); j++)
{
double v = array[column][j];
var first = new List<double> { v };
foreach (var combination in Permutations2(array, column + 1))
{
yield return first.Concat(combination);
}
}
}
But the output is not a 2D array and it uses recursion which is not efficient.
You can use a nested loop to generate all possible combinations. Here's one way to do it:
List<double[]> myArray = new List<double[]> { new double[] { 1.2, 1.3, 1.4 }, new double[] { 2.1, 2.2 }, new double[] { 3.1 } };
int rows = 1;
foreach (double[] arr in myArray) {
rows *= arr.Length;
}
double[,] result = new double[rows, myArray.Count];
int[] index = new int[myArray.Count];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < myArray.Count; j++) {
result[i, j] = myArray[j][index[j]];
}
for (int j = myArray.Count - 1; j >= 0; j--) {
index[j]++;
if (index[j] < myArray[j].Length) {
break;
}
index[j] = 0;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < myArray.Count; j++) {
Console.Write(result[i, j]);
Console.Write(";");
}
Console.Write("\n");
}
Console.ReadKey();
The code first calculates the number of rows needed in the result matrix. It then initializes a 2D double array with the correct dimensions. The index array keeps track of the current index for each array in myArray.
The outer loop generates each row in the result matrix. The inner loop sets the value of each column in the current row. After setting the value for the last column, the index array is updated. If the index for a column reaches the end of its corresponding array, it is reset to 0 and the index for the previous column is incremented.
This approach avoids recursion and generates all combinations in a single pass.