Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created April 3, 2025 23:32
Show Gist options
  • Save NickStrupat/88ed2839ced7c1547e2e961ce41254d7 to your computer and use it in GitHub Desktop.
Save NickStrupat/88ed2839ced7c1547e2e961ce41254d7 to your computer and use it in GitHub Desktop.
using System;
/// <summary>
/// A pair of 32-bit hash functions with no collisions on all 32-bit inputs
/// </summary>
/// <note>Ported from https://github.com/skeeto/hash-prospector/blob/396dbe235c94dfc2e9b559fc965bcfda8b6a122c/README.md?plain=1#L237</note>
static class PerfectHash
{
/// A perfect hash function for 32-bit integers. No collisions for all 32-bit values. The inverse of <see cref="Hash2"/>.
/// <param name="x">The integer to hash</param>
/// <returns>The hashed integer</returns>
public static UInt32 Hash(UInt32 x)
{
unchecked
{
x++;
x ^= x >> 17;
x *= 0xed5ad4bb;
x ^= x >> 11;
x *= 0xac4c1b51;
x ^= x >> 15;
x *= 0x31848bab;
x ^= x >> 14;
return x;
}
}
/// A perfect hash function for 32-bit integers. No collisions for all 32-bit values. The inverse of <see cref="Hash"/>.
/// <param name="x">The integer to hash</param>
/// <returns>The hashed integer</returns>
public static UInt32 Hash2(UInt32 x)
{
unchecked
{
x ^= x >> 14 ^ x >> 28;
x *= 0x32b21703;
x ^= x >> 15 ^ x >> 30;
x *= 0x469e0db1;
x ^= x >> 11 ^ x >> 22;
x *= 0x79a85073;
x ^= x >> 17;
x--;
return x;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment