Skip to content

Instantly share code, notes, and snippets.

@ale2x72
Created May 4, 2022 09:00
Show Gist options
  • Save ale2x72/29a3f8fb23f1f186bf5a2d396c9c059a to your computer and use it in GitHub Desktop.
Save ale2x72/29a3f8fb23f1f186bf5a2d396c9c059a to your computer and use it in GitHub Desktop.
Sequential to dimensional indices conversion
// conversion between dimensional indices for a multidimensional or jagged array to sequential index
// and vice-versa
// 2D array (nX, nY) created as [i,j] or jagged array indexed as [i][j]
// array created with nested for loops, i (nX), then j (nY) (outmost to innermost)
private int GetSequentialIndex(int i, int j, int nY) => i * nY + j;
private int[] GetDimensionalIndices(int index, int nY)
{
int[] dimIndices = new int[2];
dimIndices[0] = index / nY;
dimIndices[1] = index % nY;
return dimIndices;
}
// 3D array (nX, nY, nZ) created as [i,j,k] or jagged array indexed as [i][j][k]
// array created with nested for loops, i (nX), then j (nY), then k (nZ) (outmost to innermost)
private int GetSequentialIndex(int i, int j, int k, int nY, int nZ) => i * (nY * nZ) + j * nZ + k;
private int[] GetDimensionalIndices(int index, int nY, int nZ)
{
int[] dimIndices = new int[3];
dimIndices[0] = index / (nY * nZ);
dimIndices[1] = (index % (nY * nZ)) / nZ;
dimIndices[2] = index % (nZ);
return dimIndices;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment