OK, most probably it will be marked as duplicated, but I am looking for an answer and cannot find something similar. The question is: I want to generate random numbers within a specific range [i.e. min_value to max_value] and with a specific step. For the first part the answer is:
int random_value = rand() % max_value + min_value;
The step how can I define it? I suppose that the above mentioned solution results in step 1. Correct? And if for example I want to generate the numbers with step 2 (e.g. 2, 4, ..., 16) what should I do?
Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.
The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.
In this program we call the srand () function with the system clock, to initiate the process of generating random numbers. And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator.
This should do what you want:
int GetRandom(int max_value, int min_value, int step)
{
int random_value = (rand() % ((++max_value - min_value) / step)) * step + min_value;
return random_value;
}
Your "first step" is ill-advised since it suffers from modulo bias.
Introducing a "step" is a matter of simple arithmetic, you generate a random number on a smaller range min_value / step
to max_value / step
and multiply that by your required step (random_value * step
).
So:
#include <stdint.h>
#include <stdlib.h>
int random_range( int min_value, int max_value )
{
// Fix me
return rand() % max_value + min_value;
}
int random_range_step( int min_value, int max_value, int step )
{
return random_range( min_value / step, max_value / step ) * step ;
}
...
// (e.g. 2, 4, ..., 16)
int random_value = random_range_step( 2, 16, 2 ) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With