英文:
Flatten 3D position to 1D using width, height and length
问题
x + Width * (y + Height * z)
我可以使用仅宽度和高度来执行此操作
test:
7 + 8 * (7 + 8 * 7) = 511(预期)
这可以正常工作,但它缺少长度。
我尝试了互联网上的代码,但它们都没有包含长度,而且chatgpt给了我一个错误的代码
x + width * (y + height * z) + length * width * height * z
test:
7 + 8 * (7 + 8 * 7) + 8 * 8 * 8 * 7 = 4095(不符预期,我想要的是511)
英文:
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)
答案1
得分: 2
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:
<pre>
...
7|7|4 => 508
7|7|5 => 509
7|7|6 => 510
7|7|7 => 511
</pre>
英文:
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:
<pre>
...
7|7|4 => 508
7|7|5 => 509
7|7|6 => 510
7|7|7 => 511
</pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论