My task is to generate all possible index combinations of an array, wherein the array might be a single, 2D, 3D, 4D ... nD array with different number of elements. For now, I can only support single, 2D and 3D array using nested for loop.
Example:
byte[,,] sampleArray = new byte[5,4,3];
Generated Index Combinations:
sampleArray[0,0,0]
sampleArray[0,0,1]
sampleArray[0,0,2]
sampleArray[0,1,0]
sampleArray[0,1,1]
sampleArray[0,1,2]
sampleArray[0,2,0]
sampleArray[0,2,1]
sampleArray[0,2,2]
sampleArray[0,3,0]
sampleArray[0,3,1]
sampleArray[0,3,2]
sampleArray[1,0,0]
sampleArray[1,0,1]
sampleArray[1,0,2]
sampleArray[1,1,0]
sampleArray[1,1,1]
sampleArray[1,1,2]
sampleArray[1,2,0]
sampleArray[1,2,1]
sampleArray[1,2,2]
sampleArray[1,3,0]
sampleArray[1,3,1]
sampleArray[1,3,2]
sampleArray[2,0,0]
sampleArray[2,0,1]
sampleArray[2,0,2]
sampleArray[2,1,0]
sampleArray[2,1,1]
sampleArray[2,1,2]
sampleArray[2,2,0]
sampleArray[2,2,1]
sampleArray[2,2,2]
sampleArray[2,3,0]
sampleArray[2,3,1]
sampleArray[2,3,2]
sampleArray[3,0,0]
sampleArray[3,0,1]
sampleArray[3,0,2]
sampleArray[3,1,0]
sampleArray[3,1,1]
sampleArray[3,1,2]
sampleArray[3,2,0]
sampleArray[3,2,1]
sampleArray[3,2,2]
sampleArray[3,3,0]
sampleArray[3,3,1]
sampleArray[3,3,2]
sampleArray[4,0,0]
sampleArray[4,0,1]
sampleArray[4,0,2]
sampleArray[4,1,0]
sampleArray[4,1,1]
sampleArray[4,1,2]
sampleArray[4,2,0]
sampleArray[4,2,1]
sampleArray[4,2,2]
sampleArray[4,3,0]
sampleArray[4,3,1]
sampleArray[4,3,2]
My Code:
protected void GenerateIndexCombinations(int indexCounter,
ref List<List<int>> indexList, Array arr, ref List<int> index)
{
int dimSize1 = arr.GetLength(0);
int dimSize2 = 0;
int dimSize3 = 0;
if (indexCounter > 1)
{
dimSize2 = arr.GetLength(1);
if (indexCounter > 2)
{
dimSize3 = arr.GetLength(2);
}
}
for (int a = 0; a < dimSize1; a++)
{
if (dimSize2 > 0)
{
for (int b = 0; b < dimSize2; b++)
{
if (dimSize3 > 0)
{
for (int c = 0; c < dimSize3; c++)
{
index = new List<int>();
index.Add(a);
index.Add(b);
index.Add(c);
indexList.Add(index);
}
}
else
{
index = new List<int>();
index.Add(a);
index.Add(b);
indexList.Add(index);
}
}
}
else
{
index = new List<int>();
index.Add(a);
indexList.Add(index);
}
}
}
Where:
int indexCounter is number of dimension.
Array arr is the array accessed by using reflection:
Array arr = fieldInfoArray[j].GetValue(_classInstance) as Array;
ref List<List<int>> indexList
will be the container of the combinations.
ref List<int> index
is the individual number added to the indexList.
Since the dimension size is not fixed, as well the number of elements per dimension, I want to generate the combinations dynamically to replace my nested for loop, Is there a way to do it?
Thanks for your answers.