Home > OS >  How to implement variable number of for loops?
How to implement variable number of for loops?

Time:10-26

I have a multi-dimension array to traverse, but the dimension of this array is a variable, it could be 2 or 10 or even more, for example when dimension equals to 2, I have to traverse it like:

for (int i=0; i<size[0];   i)
  for (int j=0; j<size[1];   j)
    // do something for arr[i * size[1]   j];

and for 3-dimension arr:

for (int i=0; i<size[0];   i)
  for (int j=0; j<size[1];   j)
    for (int k=0; k<size[2];   k)
      // do something for arr[i * size[1] * size[2]   j * size[2]   k];

How to implement it in a effective way that can handle variable dimension?

CodePudding user response:

Following up on this conversation from the comments:

Alternatively, have an array of indices, and increment the bottom one and when it reaches the appropriate size, reset it to 0 and increment the next one (and so on). Probably maintain an index into the array so you don't recalculate the offset on each iteration.

Thx @PaulHankin , your solution seems like what I am looking for. By maintaining an array of indices, how to really implement it?

What you need is an array of indexes, and a set of sizes of each index, so you know when to roll over. And you need to know when you've exceeded the entire structure's last index.

In pseudocode, something like this:

numDimensions = 3 // the number of dimensions
totalSize := size[0] * size[1] * size[2] // etc, the size of the whole structure
arrayIndex := 0

// here we're assuming that size and dimensionalIndex are indexed the same way
// initialized to 0, least significant digit at index 0
dimensionalIndex := Array(numDimensions) 

while (arrayIndex < totalSize)
  
  // 
  // Access arr[arrayIndex]
  // arrayIndex should be equal to 
  // dimensionalIndex[0]   dimensionalIndex[1] * size[0]   dimensionalIndex[2] * size[0] * size[1], etc
  //

  // Increment the array counter
  arrayIndex  

  // Increment the dimensional counters (which map to your i, j, k, etc)
  dimensionalIndex[0]  = 1
  for (indexIndex = 0; indexIndex < numDimensions; indexIndex  ):
    
    // If one of the dimensions is exceeded, set it to 0 and increment the next one  
    if (dimensionIndex[indexIndex] >= size[indexIndex]) and (indexIndex < numDimensions-1):
      dimensionIndex[indexIndex 1]  
      dimensionIndex[indexIndex] = 0
    end if
  end for
end while
  • Related