Search code examples
c#3dflatten

Flatten 3D position to 1D using width, height and length


I want to flatted a 3D position to 1D using width, height and length

I can do it using only width and height using x + Width * (y + Height * z) test: 7 + 8 * (7 + 8 * 7) = 511 (expected)

And it works fine, but it misses length

I tried code from the internet but all of them miss length, and chatgpt gave me a broken one

x + width * (y + height * z) + length * width * height * z test: 7 + 8 * (7 + 8 * 7) + 8 * 8 * 8 * 7 = 4095 (not expected, I want 511)


Solution

  • Assuming you want to index a 3 dimensional room of width W x height H x length L you can index like so:

    index i = f(w,h,l) = w * (H*L) + h * L + l

    with w in [0..W[, h in [0..H[, l in [0..L[

    See this fiddle as an example: https://dotnetfiddle.net/RDI1RY

    public static int GetIndex(int x, int y, int z, int W, int H, int L)
    {
        //You could do some sanitychecking here ... 
        //if( x < 0 || x >= W ) throw new ArgumentException(nameof(x));
        // ... but the important thing is:
        return z + (y * L) + (x * H * L);
    }
    

    Output:

    ...
    7|7|4 => 508
    7|7|5 => 509
    7|7|6 => 510
    7|7|7 => 511