How do I convert a 1d index into a 3d index?

2019-09-06 16:47发布

I looked at this question: Convert a 1d array index to a 3d array index? but my result differs when I test it no matter how I calculate the index in the first place.

I am using the following to convert 3d (x,y,z) in dimensions (WIDTH, HEIGHT, DEPTH) to 1d:

i=x+WIDTH(y+HEIGHT*z)

Then to convert back from index i to (x,y,z):

z=i/(HEIGHT*WIDTH)
y=(i/WIDTH)%HEIGHT
x=i%(WIDTH)

When I test this between both methods I get the wrong results. Is there something obviously wrong with my method? What is the correct explanation?

1条回答
聊天终结者
2楼-- · 2019-09-06 17:10

here's a javascript version that works with these values:

WIDTH = 10;
HEIGHT = 20;

x = 2;
y = 4;
z = 5;

=> i = 1042

Code:

i = x + WIDTH * (y + HEIGHT * z);


z = Math.round(i / (WIDTH * HEIGHT));
y = Math.round((i - z * WIDTH * HEIGHT) / WIDTH);
x = i - WIDTH * (y + HEIGHT * z);
查看更多
登录 后发表回答