Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number in C within a range and a specific step

Tags:

c

random

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?

like image 719
kat Avatar asked Dec 15 '14 10:12

kat


People also ask

How do you generate a random number in a specific range?

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.

What is difference between rand () and Srand ()?

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.

How do you generate a random number between 1 and 10 in C?

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.


2 Answers

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;
}
like image 88
Vality Avatar answered Oct 25 '22 06:10

Vality


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 ) ;
like image 38
Clifford Avatar answered Oct 25 '22 08:10

Clifford