Created
November 18, 2015 19:16
-
-
Save Sharparam/ec653bedd9cd3acbc0d4 to your computer and use it in GitHub Desktop.
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
#include "random.h" | |
#include <assert.h> | |
#include <stdbool.h> | |
#include <stdlib.h> | |
#include <time.h> | |
void init() | |
{ | |
static bool seeded = false; | |
if (seeded) | |
return; | |
srand(time(NULL)); | |
// See: http://stackoverflow.com/a/7867148/1104531 | |
rand(); | |
seeded = true; | |
} | |
int randomInt() | |
{ | |
init(); | |
return rand(); | |
} | |
int randomMax(int max) | |
{ | |
if (max - 1 == RAND_MAX) | |
return randomInt(); | |
long end = RAND_MAX / max; | |
assert(end > 0L); | |
end *= max; | |
int r; | |
while ((r = randomInt()) >= end); | |
return r % max; | |
} | |
int randomRange(int min, int max) | |
{ | |
//return (rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min; | |
return randomMax(max) + min; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment