+ 3
Random number generator only returning the same value over
I have tried using both std::rand() % 2 and the code below: std::random_device; std::mt19937 rng(rd); std::uniform_int_distribution dist(0, 2); std::cout << dist(rng); Both codes always return 1, in sololearn at least. Does anybody know why this happens?
3 Respuestas
+ 5
If your system (or in this case, whatever machine sololearn is running on) has no "random device" for generating good quality random numbers, `std::random_device` will default to a pseudo-random number generator which can unfortunately generate the same sequence over and over again.
I don't think there is an easy way around this.
You can resort to seeding the rng with the current time like we did it in C.
std::default_random_engine eng;
unsigned long int t = std::chrono::high_resolution_clock::now().time_since_epoch().count();
eng.seed(t);
std::mt19937 rng(eng());
...
But of course this code then doesn't use better quality random numbers on systems where they are available.
Many people consider it a design flaw of <random>. I guess it is what it is.
+ 3
I did some research! Looks like you can seed the random_engine with multiple seeds.
It's not safe but maybe it's the best we can do? Not sure, I'm no expert.
https://code.sololearn.com/c2406p3RBjtz/?ref=app
- 5
Furry