Martin
Martin

Reputation: 9369

How to hash a tri-state two-dimensional array?

Consider the following code. What is a good hashing function for the array in Key to be used in an unordered_map?

#include <unordered_map>

using namespace std;

enum TriState {
    S0 = -1,
    S1 = 0,
    S2 = +1
};

struct K { // Key for the map
    TriState a[8][8];
    bool operator==(const K& k1) const {
        for (int i = 0; i < 64; i++)
            if (k1.a[0][i] != a[0][i])
                return false;
        return true;
    }
};

struct Hash {
    size_t operator()(const K& k) const {
        size_t s;
        // s = what is a good hash value?
        return s;
    }
};

unordered_map<K, int, Hash> m;

Upvotes: 5

Views: 1155

Answers (1)

Baltram
Baltram

Reputation: 681

This algorithm should be fast and provide near-uniform hashing:

size_t s = 0x3a7eb429; // Just some random seed value
for (int i = 0; i != 8; ++i)
{
    for (int j = 0; j != 8; ++j)
    {
        s = (s >> 1) | (s << (sizeof(size_t) * 8 - 1));
        s ^= k.a[i][j] * 0xee6b2807;
    }
}
s *= 0xee6b2807;
s ^= s >> 16;

After that, if you want to make the hashing even stronger, hash s another time using for example MurmurHash3.

Upvotes: 3

Related Questions