Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a hashcode of two numbers

Tags:

.net

algorithm

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

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

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

like image 260
JDunkerley Avatar asked May 21 '09 12:05

JDunkerley


People also ask

How do you create a hashCode?

If you use eclipse, you can generate equals() and hashCode() using: Source -> Generate hashCode() and equals(). Using this function you can decide which fields you want to use for equality and hash code calculation, and Eclipse generates the corresponding methods.

How is hashCode calculated?

hashcode() is computed via jvm argument -XX:hashCode=N where N can be a number from [0-5]... Depending on an application you may see unexpected performance hits when .

What does hashCode combine do?

Combines two values into a hash code.

What is hashCode number?

A hash code is an integer value that is associated with each object in Java. Its main purpose is to facilitate hashing in hash tables, which are used by data structures like HashMap.


1 Answers

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 

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

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) 

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

like image 61
Jon Skeet Avatar answered Nov 19 '22 18:11

Jon Skeet