3D向量的哈希值 [英] Hash Value for 3D Vector
问题描述
有没有一种方法可以将3D矢量表示为定数?我的意思是两个具有不同值的向量永远不会具有相同的哈希值.我敢肯定已经有一个问题了,但不幸的是我没有找到它.感谢您的帮助.
Is there a way to represent a 3D Vector as a definite number? I mean that two vectors with different values can't ever have the same hash value. I'm sure there already is a question about this but I haven't found it unfortunately. Thanks for your help.
我知道这种用于2D向量的算法非常好(我认为):(x + y) * (x + y + 1) / 2 + y
I know this algorithm for 2D vectors which is pretty good (I think): (x + y) * (x + y + 1) / 2 + y
推荐答案
请参见鸽子洞原理-用同样的方法,您无法容纳100羽鸽子进入10洞,也无法将3个值唯一地转换为1个值(所有值均相同).必须有重复项.
See the pigeon-hole principle - in the same way you can't fit you can't 100 pigeons into 10 holes, you can't uniquely convert 3 values into 1 value (with all values of the same size). There will have to be duplicates.
现在,如果您的数字位数可以是向量值的3倍,那么问题就变得很简单了:
Now, if you could have a number with 3x as many bits as the vector values, the problem becomes fairly easy:
// convert x, y and z to the range 0-...
x -= minimum possible value
y -= minimum possible value
z -= minimum possible value
mult = maximum possible value + 1
hash = x * mult * mult + y * mult + z
如果您在理解上述内容时遇到困难,请以数值范围为0-99的示例为例.我们将x
乘以100*100 = 10000
,将y
乘以100
,因此哈希将是一个十进制值,最多包含6个数字,其中x
,y
和z
都紧随其后彼此,保证不会重叠:
If you're having trouble understanding the above, just take the example of the range of the values being 0-99. We'd multiple x
by 100*100 = 10000
and y
by 100
, so the hash would be a decimal value with (at most) 6 digits with x
, y
and z
all next to each other, guaranteed to not overlap:
x = 12
y = 34
z = 56
hash = 123456
现在,只需更改基数/基数,该想法就可以保持任何最大值.
Now this same idea will hold for any maximum value by just changing the base / radix.
如果某个基数中没有任何重叠,则x
,y
和z
值的每个唯一组合将导致唯一的哈希.
If there isn't any overlap in some base, each unique combination of values of x
, y
and z
will result in a unique hash.
这是迄今为止最简单的方法,尽管它不会产生特别好的 哈希,因此这取决于您要使用的哈希值-可能有一种方法可以唯一地转换此数字到另一个数字,这将是一个很好的哈希值.
This is by far the simplest approach, although it doesn't produce a particularly good hash, so it depends what you want to use it for - there might be a way to uniquely convert this number to another number which will be a good hash.
这篇关于3D向量的哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!