How to dynamically calculate an index?

ananymouse anony at mouse.com
Tue Jul 12 14:17:36 UTC 2022


Given a 3D matrix of shape[3, 5, 7] that is implemented using a 
1D array, I can calculate the index of any element (e.g. [1, 0, 
6]) as follows:

     index = 1 * 5 * 7 + 0 * 7 + 6

In general, if I have a K x L x M matrix, I can access 
index[i][j][k] by calculating i*L*M + j*M + k to yield the index. 
Likewise, when working with a 4D matrix[h][i][j][k], I can 
achieve the same by calculating h*L*M*N + i*M*N + j*N + k.

If I have both the index ([i, j, k]) and the shape ([K, L, M]) 
stored in two separate arrays of equal length, how could I 
dynamically generate the above calculations for any two such 
arrays of arbitrary length 3 or greater?

Been racking my brain on this for hours. Please point me in the 
right direction.

Thanks,
--anonymouse




More information about the Digitalmars-d-learn mailing list