Last active
April 26, 2025 21:22
-
-
Save bbarry/cc1398cf46b513845efdace300ea2fd1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* Disclaimer: I don't think I have written C in 30 years. */ | |
static uint32_t randval = 0; | |
static uint32_t shift = 30; | |
static uint32_t next_d32() { | |
/* pull 6 5-bit random numbers out of every 31 bit random() call */ | |
uint32_t result; | |
if (shift >= 30) { | |
randval = random(); | |
shift = 0; | |
} | |
result = (randval >> shift) & 0x1F; | |
shift = shift + 5; | |
return result; | |
} | |
static uint32_t next_d20() { | |
uint32_t result; | |
do { | |
result = next_d32(); | |
} while (result >= 20); | |
return result; | |
} | |
/* ----- alternative that trades the loop for 3 ops and more frequent random() calls (if it is stil unbiased) ----- */ | |
static uint32_t randval = 0; | |
static uint32_t shift = 30; | |
static uint32_t next_d64() { | |
/* pull 5 6-bit random numbers out of every 31 bit random() call */ | |
uint32_t result; | |
if (shift >= 30) { | |
randval = random(); | |
shift = 0; | |
} | |
result = (randval >> shift) & 0x3F; | |
shift = shift + 6; | |
return result; | |
} | |
static uint32_t next_d20() { | |
uint32_t result = next_d64(); | |
return (result & 3) + (result >> 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment