Created
June 27, 2011 22:44
-
-
Save michaelficarra/1050039 to your computer and use it in GitHub Desktop.
fair pseudo-random number generation in C
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
| 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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: the function may need to be named something other than
random.