简体   繁体   English

将1d数组索引转换为3d数组索引?

[英]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. 我有一个int想要转换为3个int用于3d数组的索引,这里是我所关注的一个例子。

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. . 假设您想要遍历Z,然后是Y,然后是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: 假设您将数字映射为0,对应于0,0,0,并且您迭代z,则y,然后x,数学非常简单:

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. 请注意,这比BlackVegetable的解决方案节省了一些冗余操作。 For a (3, 3, 3) matrix, this yields the set: 对于(3,3,3)矩阵,这会得到集合:

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 . 此外,这是可逆的, i = z + y * ZSize + x * ZSize * YSize

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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