Created
September 20, 2019 14:54
-
-
Save lucis/96dc883af28c037104ef42ecedb8c3bf to your computer and use it in GitHub Desktop.
Random in clang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This function generates a random number between 0 and `max` | |
// Original method: http://goo.gl/At4AIC | |
int | |
random(int max) { | |
if (max <= 0) { | |
return 1; | |
} | |
static int z1 = 12345; // 12345 for rest of zx | |
static int z2 = 12345; // 12345 for rest of zx | |
static int z3 = 12345; // 12345 for rest of zx | |
static int z4 = 12345; // 12345 for rest of zx | |
int b; | |
b = (((z1 << 6) ^ z1) >> 13); | |
z1 = (((z1 & 4294967294) << 18) ^ b); | |
b = (((z2 << 2) ^ z2) >> 27); | |
z2 = (((z2 & 4294967288) << 2) ^ b); | |
b = (((z3 << 13) ^ z3) >> 21); | |
z3 = (((z3 & 4294967280) << 7) ^ b); | |
b = (((z4 << 3) ^ z4) >> 12); | |
z4 = (((z4 & 4294967168) << 13) ^ b); | |
// if we have an argument, then we can use it | |
int rand = ((z1 ^ z2 ^ z3 ^ z4)) % max; | |
if (rand < 0) { | |
rand = rand * -1; | |
} | |
return rand; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment