Question

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?

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top