Home > OS >  Change value of randomly generated number upon second compilation
Change value of randomly generated number upon second compilation

Time:07-20

I applied the random number generator to my code although the first number generated doesn't change when I run the code second or the third time. The other numbers change however and the issue is only on the first value. I'm using code blocks; Cygwin GCC compiler (c 17). Seeding using time.

#include <iostream> 
#include <random>
#include <ctime>
    
int main()
{
    std::default_random_engine randomGenerator(time(0));
    std::uniform_int_distribution randomNumber(1, 20);
    int a, b, c;
    a = randomNumber(randomGenerator); 
    b = randomNumber(randomGenerator); 
    c = randomNumber(randomGenerator);
    std::cout<<a<<std::endl;
    std::cout<<b<<std::endl;
    std::cout<<c<<std::endl;

    return 0;
}

In such a case when I run the code the first time it may produce a result like a = 4, b = 5, c = 9. The second and further time (a) remains 4 but (b) and (c) keep changing.

CodePudding user response:

Per my comment, the std::mt19937 is the main PRNG you should consider. It's the best one provided in <random>. You should also seed it better. Here I use std::random_device.

Some people will moan about how std::random_device falls back to a deterministic seed when a source of true random data can't be found, but that's pretty rare outside of low-level embedded stuff.

#include <iostream>
#include <random>

int main() {
  std::mt19937 randomGenerator(std::random_device{}());
  std::uniform_int_distribution randomNumber(1, 20);

  for (int i = 0; i < 3;   i) {
    std::cout << randomNumber(randomGenerator) << ' ';
  }
  std::cout << '\n';

  return 0;
}

Output:

~/tmp 
❯ ./a.out 
8 2 16 

~/tmp 
❯ ./a.out
7 12 14 

~/tmp 
❯ ./a.out
8 12 4 

~/tmp 
❯ ./a.out
18 8 7

Here we see four runs that are pretty distinct. Because your range is small, you'll see patterns pop up every now and again. There are other areas of improvement, notably providing a more robust seed to the PRNG, but for a toy program, this suffices.

  •  Tags:  
  • c
  • Related