-
I'm working on a procedural generation project and would like the randomness to be deterministic based on points in a grid and order independent. I thought about using MurmurHash3 since all of my points will be uint32. I'm unsure if I need to XOR the hash by the number of uint32 or the number of bytes. Do you have any thoughts? /**
* The number of bits in an unsigned 32 bit integer.
*/
const UINT32_SIZE = 32;
/**
* The maximum unsigned 32 bit integer.
*/
const MAX_UINT32 = uint32(Math.pow(2, 32) - 1);
/**
* Converts a number to a 32 bit unsigned integers.
*/
function uint32(value: number): number {
return value >>> 0;
}
/**
* Rotates the bits of a number
*/
function rol(value: number, bits: number) {
return (value << bits) | (value >>> (UINT32_SIZE - bits));
}
/**
* Calculates the murmur hash for a tuple of 32 bit unsigned integers.
*/
function murmurhash3(values: number[], seed: number = 0): number {
let hash = uint32(seed);
for (const value of values) {
let k = uint32(value);
k = Math.imul(k, 0xcc9e2d51);
k = rol(k, 15);
k = Math.imul(k, 0x1b873593);
hash ^= k;
hash = rol(hash, 13);
hash = uint32(Math.imul(hash, 5) + 0xe6546b64);
}
// I'm unsure how important is it to multiply the length or not
hash ^= Math.imul(values.length, 4);
hash ^= hash >>> 16;
hash = Math.imul(hash, 0x85ebca6b);
hash ^= hash >>> 13;
hash = Math.imul(hash, 0xc2b2ae35);
hash ^= hash >>> 16;
return uint32(hash);
}
/**
* Calculates a "random" value based on a tuple of 32 bit unsigned integers
*/
function random(values: number[]): number {
return murmurhash3(values) / MAX_UINT32;
} |
Beta Was this translation helpful? Give feedback.
Answered by
bryc
Oct 14, 2021
Replies: 1 comment 1 reply
-
MurmurHash3 assumes the input array to be |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
pspeter3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MurmurHash3 assumes the input array to be
uint8
, so the length of the array is in bytes. Assuming an array ofuint32
, multiply that length by 4.