Skip to content

Instantly share code, notes, and snippets.

@Sharparam
Created November 18, 2015 19:16
Show Gist options
  • Save Sharparam/ec653bedd9cd3acbc0d4 to your computer and use it in GitHub Desktop.
Save Sharparam/ec653bedd9cd3acbc0d4 to your computer and use it in GitHub Desktop.
#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