Skip to content

Instantly share code, notes, and snippets.

@michaelficarra
Created June 27, 2011 22:44
Show Gist options
  • Select an option

  • Save michaelficarra/1050039 to your computer and use it in GitHub Desktop.

Select an option

Save michaelficarra/1050039 to your computer and use it in GitHub Desktop.
fair pseudo-random number generation in C
int random(int min, int max) {
if(min == max) return min;
if(min > max) {
int tmp = max;
max = min;
min = tmp;
}
int range = max - min + 1;
int randMax = RAND_MAX - ((RAND_MAX - range + 1) % range);
int rnd;
do {
rnd = rand();
} while(rnd > randMax);
return (rnd % range) + min;
}
@michaelficarra
Copy link
Author

Note: the function may need to be named something other than random.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment