2

First of all, I found an implementation of GetHashCode for a 3D integer vector, but I can't figure out if this is a good one or not (at least I'm not 100% sure):

public struct Vector3i
{
    public int x;
    public int y;
    public int z;

    public override int GetHashCode ()
    {
        return x.GetHashCode () ^ y.GetHashCode () << 2 ^ z.GetHashCode () >> 2;
    }
}

From this, I would like to create a pair of 3D vectors (let's call them A and B) with a hashcode which is independent from the order of Vectors A and B. In other words I want the pair (A, B) to have the same hashcode than the pair (B, A). I thought of something like this:

public struct Vector3iPair
{
    public Vector3i a;
    public Vector3i b;

    public override int GetHashCode ()
    {
        return a.GetHashCode () ^ b.GetHashCode ();
    }
}

Do you think this would have the correct behavior?

NWard
  • 2,016
  • 2
  • 20
  • 24
Casto
  • 305
  • 4
  • 10

1 Answers1

1

Please reference this answer for a correct implementation of the GetHashCode(), as it's suitable for your question as well.

As for your second part of the question, it should work fine as the bitwise xor (^) is commutative, meaning you'll get same result regardless of order of operations.

However, the question arises, are you just going to put your vectors into Hashmaps or do you have some different spatial hashing approach in mind?

Community
  • 1
  • 1
Alex
  • 923
  • 9
  • 21
  • Thanks Alex, this is the answer I needed. I want the vector-pair to be commutative (regarding hashcode) because I need to be able to store and retrieve stuff happening between A and B, regardless their order. To be more specific, I have a method that creates a vertex between two given points and I don't want to duplicate vertices, so if a vertex between the two points already exists, I have to be able to retrieve it quickly. – Casto Dec 30 '13 at 15:14
  • I'd suggest using addition rather than xor, or else combine hash codes x and y with something like `(x^y^((x+y)*251))`. With a simple xor-based hash, half of all vector pairs {(a,b,c),(a,b+1,c)} will yield a hashcode value of 1. Not good. Using the above approach will make the hash value depend upon all the values. – supercat Dec 30 '13 at 20:34