How to iterate over n dimensions?
algorithm, arrays, dimension, loops
Solution
Python code:
def nd_range(start, stop, dims):
if not dims:
yield ()
return
for outer in nd_range(start, stop, dims - 1):
for inner in range(start, stop):
yield outer + (inner,)
Example:
print(list(nd_range(0, 3, 3)))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]
Problem
How can I iterate over a n-dimensional array given the number of dimensions and the size of each as variables? ``` int n; int size[n]; ``` Since the number of dimensions is not fixed, I cannot write a nested loop for each dimension. I need the code to work with each number of dimensions. In addition, it doesn't matter weather the actual data is stored in a n-dimensional array or a flat array containing all the data in a large row. Both are acceptable. ``` int data[16][42][14]; // n-dimensional array int data[16 * 42 * 14]; // flat array containing the same data ```