Skip to content

Instantly share code, notes, and snippets.

@guipn
Created March 9, 2012 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guipn/2008699 to your computer and use it in GitHub Desktop.
Save guipn/2008699 to your computer and use it in GitHub Desktop.
Random integer within given range
#include <time.h>
unsigned int uirndrng(unsigned int low, unsigned int high)
{
static char randomized;
if (low >= high)
{
exit(EXIT_FAILURE);
}
if (randomized == 0)
{
srand(time(NULL));
randomized = 1;
}
// As suggested by c-faq.com:
return low + rand() / (RAND_MAX / (high - low + 1) + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment