range


C/C++: Get a random number that is in a specific range 1

Assuming you need to generate a random number that is in a specified range, you can do the following:


//int rand(void) creates a pseudo-random number in the range of 0 to RAND_MAX
//RAND_MAX is defined in stdlib.h and is the largest number rand will return (same as INT_MAX).
const int new_number = (rand() % (maximum_number + 1 - minimum_number)) + minimum_number;

The above code first creates a pseudo-random number that is in the range of [0, RAND_MAX].
Then it will divide it with the width (+1) of the range we want to use (maximum_number + 1 - minimum_number) and get the remainder (modulo).
The modulo will be in the range of [0, maximum_number - minimum_number], so we add to it the value of minimum_number to shift the result to the proper range.
This solution, as demonstrated in the example below, works for negative ranges as well.

Full example of generating 100000 random numbers that are all in the range [-31, 32].

const int maximum_number = 31;
const int minimum_number = -32;
unsigned int i;
for (i = 0; i <= 100000; i++) {
	const int new_number = (rand() % (maximum_number + 1 - minimum_number)) + minimum_number;
	printf("%d\n", new_number);
}

Bash: Get random number that belongs in a range 1

In case you need to create a random number that is between a certain range, you can do it in a very easy way in bash.

Bash has the $RANDOM internal function that returns a different (pseudo) random integer at each invocation. The nominal range of the results is 0 – 32767 (it is the range of a signed 16-bit integer).

We use the result of $RANDOM to create our number using the following script:

FLOOR=10;
CEILING=100;
RANGE=$(($CEILING-$FLOOR+1));
echo "You will generate a random number between $FLOOR and $CEILING (both inclusive). There are $RANGE possible numbers!"
RESULT=$RANDOM;
echo "We just generated the random number $RESULT, which might not be in the range we want";
let "RESULT %= $RANGE";
RESULT=$(($RESULT+$FLOOR));

echo "Congratulations! You just generated a random number ($RESULT) the is in between $FLOOR and $CEILING (inclusive)";

We use basic math operations on the variables to create the random number that is in the range we like without need-less loops.

What we do is:

  1. We compute the length of the range of valid numbers (ceiling-floor)
    Here we added the +1 because we want the ceiling to be included in the result set.
  2. We generate a random number that is between 0 and the length of range using modulo to limit the results.
  3. We add to the result the value of the floor and this create our final result which is a number equal or greater to the floor and equal or smaller to the ceiling