Skip to content

Instantly share code, notes, and snippets.

@dmundt
Created January 18, 2013 08:37
Show Gist options
  • Save dmundt/4563185 to your computer and use it in GitHub Desktop.
Save dmundt/4563185 to your computer and use it in GitHub Desktop.
C: Create semi-open interval [min, max).
// 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