创建两个数字的哈希码 [英] Create a hashcode of two numbers

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

问题描述

我正在尝试为 C# 中的复数类 (a + b) 创建一个快速哈希码函数.

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

我反复看到了 a.GetHashcode()^b.GetHashCode() 方法.但这将为 (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 框架中是否有任何函数可以提供帮助?

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

推荐答案

我为任意一组可散列项创建散列码的常规方法:

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)

如果您更多地了解 ab 的实际值可能是什么,您可能会做得更好,但这是一个很好的初始实现,很容易记住并执行.请注意,如果您有可能在检查算术溢出/下溢"的情况下构建程序集,则应将其全部放入未检查的块中.(溢出对于这个算法来说很好.)

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.)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆