Search code examples
c++indexinglogarithm

Index arithmetic - Fast converting index to 3D coordinates


What is the fastes way in C++ to convert an index with such a formation to X, Y and Z coordinates and back ?

EDIT:

I want for example get for the index 15 the numbers X=0, Y=1, Z=2, for the index 17 the numbers X=2, Y=1, Z=2, and for the index 22 the numbers X=1, Y=2, Z=1.

I need this to emulate a multidimensional array.

enter image description here


Solution

  • To:

    x = index % 3;
    y = index / 3  % 3;
    z = index / 9;
    

    Back:

    index = ((z) * 3 + y) * 3 + x;