0
\$\begingroup\$

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:

enter image description here

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.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – Pikalek
    Jun 22 '21 at 21:42
  • \$\begingroup\$ @Pikalek it's not homework, it just needs to be as optimized as possible. \$\endgroup\$ Jun 23 '21 at 7:25
0
\$\begingroup\$

This is trivial.

i = z + y * CubesPerColumn + x * CubesPerSlice

In your diagram,

CubesPerColumn = 3

and

CubesPerSlice = CubesPerColumn * ColumnsPerSlice = 3 * 4 = 12
\$\endgroup\$
0
\$\begingroup\$

It's a geometric progression. Here's a working formula:

i = z + y * maxZ + x * maxY * maxZ
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .