I need to generate random numbers between two values in c , which can be generated like that(in a range 1 to 6) :
#include <iostream>
#include <random>
int main(int argc, char* argv[]){
srand(time(NULL));
for (int j = 0; j < 6 ; j ) {
randomNumber = rand() % 6 1;
cout << randomNumber;
return 0;
}
But I also need to ensure that it generates at least once each number in the range, for example: range [1,6], you must generate at least once the 1,2,3,4,5 and 6.
And there is another thing, the numbers generated, must be evenly distributed, like if want generate 20 iterations in range of[1,6], each number(1,2,3,4,5,6) should have approximately the same quantity generated at 20 iterations. Example: 1,3,5,2,4,6,2,4,6,1,3,5,6,5,4,3,5,2,1.... and not like this: 1,3,5,6,6,6,2,6,4,4,4,4,4,4...
If anyone knows how to solve this, I'll be very grateful to you. Thanks!!!
CodePudding user response:
This is where the C Standard Library comes to the rescue. Typed off the top of my head:
#include <random>
int get_rand_in_1_6()
{
static std::random_device rnd;
return std::uniform_int_distribution <int> ( rnd )( 1, 6 );
}
The result will be uniformly-distributed.
(You may not get one of each in the first six iterations, though. Being uniformly distributed does not guarantee any specific values in any specific sub-interval, only that the number is just as likely as any other to appear. Given enough iterations, you will see that.)
[edit 2]: IDR the exact mathematical formula for minimum number of iterations to guarantee that you see each number at least once — I am wildly guessing around 15 for the minimum number of pulls to guarantee that.
CodePudding user response:
If I understand correctly, std::shuffle
might help you:
std::random_device rd;
std::mt19937 gen(rd());
int numbers[] = {1, 2, 3, 4, 5, 6};
for (int j = 0; j < 20 ; j ) {
if (j % 6 == 0) { std::shuffle(numbers, numbers 6, gen); }
std::cout << numbers[j % 6];
}
You have then sequence of random permutations.