我有一个整数,我想将其转换为 3 个整数作为 3d 数组的索引,这是我正在讨论的一个示例。
byte[,,] array = new byte[XSize, YSize, ZSize];
int i = 0;
//other code
array[#,#,#] = cur;
//other code
我不知道如何从 i 中获取 #,#,# 的正确数字。
我有一个整数,我想将其转换为 3 个整数作为 3d 数组的索引,这是我正在讨论的一个示例。
byte[,,] array = new byte[XSize, YSize, ZSize];
int i = 0;
//other code
array[#,#,#] = cur;
//other code
我不知道如何从 i 中获取 #,#,# 的正确数字。
假设您要遍历 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:
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
.