Skip to content

Instantly share code, notes, and snippets.

@0x00b1
Created June 2, 2013 18:18
Show Gist options
  • Save 0x00b1/5694347 to your computer and use it in GitHub Desktop.
Save 0x00b1/5694347 to your computer and use it in GitHub Desktop.
// Write a C function whose return value is an integer between one and five:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int sample(int minimum, int maximum)
{
int random = rand();
int range = maximum - minimum;
if (RAND_MAX == random)
{
return sample(minimum, maximum);
}
if (random < RAND_MAX - (RAND_MAX % range))
{
return minimum + random / (RAND_MAX / range);
}
else
{
return sample(minimum, maximum);
}
}
int main(int argc, const char * argv[])
{
srand(time(NULL));
printf("%d", sample(1, 5));
return 0;
}
/*
Write a C function whose return value is an integer between one and seven:
int main(int argc, const char * argv[])
{
srand(time(NULL));
printf("%d", sample(1, 7));
return 0;
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment