将3D位置使用宽度、高度和长度压缩为1D。

huangapple go评论73阅读模式
英文:

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 &lt; 0 || x &gt;= 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>

huangapple
  • 本文由 发表于 2023年6月6日 16:45:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定