简体   繁体   中英

Convert a 1d array index to a 3d array index?

I've got a int that I want to convert to 3 ints for the index of a 3d array, here's an example of what I'm on about.

byte[,,] array = new byte[XSize, YSize, ZSize];

int i = 0;

//other code

array[#,#,#] = cur;

//other code

I don't know how to get the correct numbers for the #,#,# from just i.

Supposing you want to iterate through Z, then Y, and then X. . .

int zDirection = i % zLength;
int yDirection = (i / zLength) % yLength;
int xDirection = i / (yLength * zLength); 

You have to make an assumption about the orientation of the array-space. Assuming you are mapping the numbers with 0 corresponding to 0, 0, 0, and that you iterate z, then y, then x, the math is fairly simple:

int x;
int y;
int z;

if (i < XSize * YSize * ZSize)
{
    int zQuotient = Math.DivRem(i, ZSize, out z);
    int yQuotient = Math.DivRem(zQuotient, YSize, out y);
    x = yQuotient % XSize;
}

Note that this saves some redundant operations over BlackVegetable's solution. For a (3, 3, 3) matrix, this yields the set:

i (x, y, z)
0 (0, 0, 0)
1 (0, 0, 1)
2 (0, 0, 2)
3 (0, 1, 0)
4 (0, 1, 1)
5 (0, 1, 2)
6 (0, 2, 0)
7 (0, 2, 1)
8 (0, 2, 2)
9 (1, 0, 0)
10 (1, 0, 1)
11 (1, 0, 2)
12 (1, 1, 0)
13 (1, 1, 1)
14 (1, 1, 2)
15 (1, 2, 0)
16 (1, 2, 1)
17 (1, 2, 2)
18 (2, 0, 0)
19 (2, 0, 1)
20 (2, 0, 2)
21 (2, 1, 0)
22 (2, 1, 1)
23 (2, 1, 2)
24 (2, 2, 0)
25 (2, 2, 1)
26 (2, 2, 2)

Also, this is reversible with i = z + y * ZSize + x * ZSize * YSize .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM