本文介绍了创建两个数字的哈希值code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个快速哈希code函数的复数类(A + B)在C#。

I am trying to create a quick hashcode function for a complex number class (a + b) in C#.

我见过多次了 a.GetHash code()^ b.GetHash code()方法。但是,这会产生相同的哈希值$ C $下(A,B)(B,A)

I have seen repeatedly the a.GetHashcode()^b.GetHashCode() method. But this will give the same hashcode for (a,b) and (b,a).

有没有标准的算法来做到这一点,是否有.NET Framework中的任何功能,以帮助?

Are there any standard algorithm to do this and are there any functions in the .Net framework to help?

推荐答案

我的正常建立一个哈希code的任意一组哈希项的方式:

My normal way of creating a hashcode for an arbitrary set of hashable items:

int hash = 23;
hash = hash * 31 + item1Hash;
hash = hash * 31 + item2Hash;
hash = hash * 31 + item3Hash;
hash = hash * 31 + item4Hash;
hash = hash * 31 + item5Hash;
// etc

在你的情况 item1Hash 可能仅仅是 A item2Hash 可能仅仅是 B

In your case item1Hash could just be a, and item2Hash could just be b.

23和31的值是比较不重要的,只要它们是素数(或至少互质)。

The values of 23 and 31 are relatively unimportant, so long as they're primes (or at least coprime).

显然仍然会有冲突,但你没有碰到的正常讨厌的问题:

Obviously there will still be collisions, but you don't run into the normal nasty problems of:

hash(a, a) == hash(b, b)
hash(a, b) == hash(b, a)

如果你知道更多关于什么的实际值 A B 很可能是你也许可以做到更好的,但是这是一个很好的初步实现,它是很容易记住并执行。请注意,如果有,你会与建立装配任何机会检查算术溢/下溢打勾,你应该把它全部在unchecked块。 (溢出是罚款,这种算法。)

If you know more about what the real values of a and b are likely to be you can probably do better, but this is a good initial implementation which is easy to remember and implement. Note that if there's any chance that you'll build the assembly with "check for arithmetic overflow/underflow" ticked, you should put it all in an unchecked block. (Overflow is fine for this algorithm.)

这篇关于创建两个数字的哈希值code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:46