Random number generator only returning the same value over | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

21st Apr 2019, 9:03 PM
someUser
3 Answers
+ 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.
21st Apr 2019, 9:31 PM
Schindlabua
Schindlabua - avatar
+ 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
21st Apr 2019, 10:01 PM
Schindlabua
Schindlabua - avatar
- 5
Furry
22nd Apr 2019, 8:51 PM
Feesal Ali Adm
Feesal Ali Adm - avatar