# In a 3D grid of cubes, how to calculate index of a cube if we only know it's coordinates and the way cubes are generated?

I have a code that generates a grid of equally sized cubes in a cubic volume of given limited size, intended to be used for 3d path finding. Let's say cubes are objects stored in an array called Grid[]. I need to mathematically retrieve an index of the cube in that array, when knowing only it's X, Y and Z coordinates.

As an example, imagine a volume that can fit 6 cubes in length (X), 4 cubes in width (Y), and 3 cubes in height (Z). That's a total of 72 cubes. That means every cube has it's unique X, Y and Z coordinates; {0, 0, 0} for the first cube (Grid[0]), all the way to the {5, 3, 2} for the last cube (Grid[71]).

The cubes are generated by filling the Z axis upwards, than the Y axis, and lastly the X. Here's a drawing to explain it better:

What mathematical formula can I use to calculate the i by using cube's X, Y and Z coordinates, and the volume's maximum X, Y and Z values?

I am not allowed to have a separate HashMap to look through it. I am also not supposed to loop through all of the array members and compare the stored values with the given coordinates - the grid could contain millions of cubes.

• The phrases "not allowed to" & "not supposed to" suggest that this might be homework. If that's the case, it is okay to ask about homework, but you should acknowledge that in your question text & you can review our other homework guideline here. Jun 22 at 21:42
• @Pikalek it's not homework, it just needs to be as optimized as possible. Jun 23 at 7:25

This is trivial.

i = z + y * CubesPerColumn + x * CubesPerSlice