I want to generate a random number between multiple ranges in C. Also I want to take the input from user for the number of ranges. I do have a function for generating random number within one range, can I use that function to generate such multiple ranges? Please Help.
3 Answers
Since you already have a way to generate a random number within one range, you can certainly generate it between two ranges:
First, determine how many possible values there are.
int num_values = 1 + range1high - range1low;
num_values += (1 + range2high - range2low);
// continue for additional ranges
Next generate a random number between 0 and num_values.
Finally, adjust that number based on the base of range 1's low. If it exceeds range 1's high, subtract the size of range 1 and re-base it on range 2. Continue to re-base for additional ranges.
The following program has a hard coded sample of generating a number in the ranges [2,5] or [100,200], and an exercise that generates enough data to normally hit every value within the valid ranges. This function could be improved upon significantly, but it works fine for a hard-coded set of ranges:
#include <stdio.h>
#include <stdlib.h>
int randomInRanges()
{
int range1low = 2, range1high = 5;
int range2low = 100, range2high = 200;
int range1size = 1 + range1high - range1low;
int range2size = 1 + range2high - range2low;
int numValues = range1size + range2size;
int rawRandom = rand() % (numValues);
/* is the value within range 1? */
if (rawRandom < range1size) return range1low + rawRandom; /* return a range 1 value */
rawRandom -= range1size;
/* is it in range 2? */
if (rawRandom < range2size) return range2low + rawRandom; /* return a range 2 value */
rawRandom -= range1size; /* not necessary since we've seen the last range, but part of the pattern */
printf("Impossible!\n");
exit(0);
return -1;
}
int main(int argc, char *argv[])
{
int values[300] = {0, };
int i;
/* seed the random number generator */
srand(time(NULL));
for (i = 0; i < 10000; ++i)
{
values[randomInRanges()]++;
}
for (i = 0; i < 300; ++i)
{
if (values[i]) printf("[%d]: %d\n", i, values[i]);
}
return 0;
}
8 Comments
num_values should get set to 1 + range1high - range1low. Looking at CiaPan's numbers, assuming the true random number was 6, you would want to select 100. He suggests 100+x-3, which is range2low + randomnum = num_values but like me, he is off by one; there are 4 values in the bottom range.What I suggest you do is select a range randomly, then, generate the number within that range.
srand(time(NULL));
int r = rand() % 3; //supposing we have 3 ranges to choose from
int min;
int max;
switch(r) {
case(0): // [1, 4]
min = 1;
max = 4;
case(1): // [6, 7]
min = 6;
max = 7;
case(2): // [10, 15]
min = 10;
max = 15;
}
int range = max - min;
r = (rand() % range) + min;
[1, 4]or[6, 7], but not(5, 6)?