Generate random number in C within range and specific step

OK, most likely, it will be marked as duplicated, but I am looking for an answer and can not find something like that. The question arises: I want to generate random numbers in a certain range [t. 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; 

How can I identify it? I believe the above solution leads to step 1. Is this correct? And if, for example, I want to generate numbers in steps of 2 (for example, 2, 4, ..., 16), what should I do?

+5
source share
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; } 
+3
source

Your β€œfirst step” is not recommended, as it suffers from modulo bias .

Introducing a β€œstep” is a matter of simple arithmetic, you generate a random number in a smaller range from min_value / step to max_value / step and multiply it by the 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 ; } ... // (eg 2, 4, ..., 16) int random_value = random_range_step( 2, 16, 2 ) ; 
+2
source

Source: https://habr.com/ru/post/1209081/


All Articles