Created
January 18, 2013 08:37
-
-
Save dmundt/4563185 to your computer and use it in GitHub Desktop.
C: Create semi-open interval [min, max).
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
// Create semi-open interval [min, max). | |
int random_in_range(unsigned int min, unsigned int max) { | |
int base_random = ::rand(); // in [0, RAND_MAX] | |
if (RAND_MAX == base_random) { | |
return random_in_range(min, max); | |
} | |
// Now guaranteed to be in [0, RAND_MAX). | |
int range = max - min; | |
int remainder = RAND_MAX % range; | |
int bucket = RAND_MAX / range; | |
// There are range buckets, plus one smaller interval | |
// within remainder of RAND_MAX. | |
if (base_random < RAND_MAX - remainder) { | |
return min + base_random / bucket; | |
} else { | |
return random_in_range(min, max); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment