Reputation: 95
I am looking for a random number generator with 3 inputs for a terrain generator. The inputs are an x, y (position) and a seed value. And the function returns back a random number from 0-1.
So far I found this question, but this has 2 inputs. Although I can combine x and y to a single number, to get two inputs, this will restrict the choices I will have for x, y as they need to be sufficiently large (the terrain is infinite).
Is there any random function that takes in 3 inputs, or would I need to end up using the 2 input version?
Upvotes: 2
Views: 756
Reputation: 1303
Something like this should work. It takes three 32-bit integers, and outputs a single 32-bit integer. If you want to turn the output into a double between 0 and 1, just divide by UINT32_MAX
.
The input and output sizes can be adjusted.
You can also tweak the balance between output quality and speed. You'll notice that the middle section is just repeated 3 lines, remove or add more of them to make the output more or less biased.
Here's the C code.
uint32_t rotl32(uint32_t n, uint8_t k) {
uint32_t a = n << k;
uint32_t b = n >> (32 - k);
return a | b;
}
uint32_t three_input_random(uint32_t x, uint32_t y, uint32_t z) {
uint32_t a = x;
uint32_t b = y;
uint32_t c = z;
b ^= rotl32(a + c, 7);
c ^= rotl32(b + a, 9);
a ^= rotl32(c + b, 18);
b ^= rotl32(a + c, 7);
c ^= rotl32(b + a, 9);
a ^= rotl32(c + b, 18);
b ^= rotl32(a + c, 7);
c ^= rotl32(b + a, 9);
a ^= rotl32(c + b, 18);
return a + b + c + x + y + z;
}
Upvotes: 2