0
Why is my Random function not working?
https://code.sololearn.com/cC6LlNe7zCvi/?ref=app I am unable to figure out why the function produces the same result every time in a runthrough, can someone help me out there?
4 Respostas
+ 4
It's because you seed the generator every time you call a function.
Keep in mind that time returns the time in seconds and this only changes once per second, so if you call the function many times in a second you get the same seed and this then generates the same number.
Instead you can put the generator inside the private part and seed it only once in the constructor.
+ 2
I posted a similar answer here:
https://www.sololearn.com/Discuss/889003/how-rand-function-works-in-a-program-pease-explain-anyone
Maybe if you see the function it'll help a bit :)
Of course this function is just for the basic rand() and the algorithm for the default_random_engine generator is probably different, I don't know which algorithm that that generator uses.
Personally I usually use the std::mt19937 generator which works using the Mersenne Twister algorithm.
http://www.cplusplus.com/reference/random/mt19937/
https://en.wikipedia.org/wiki/Mersenne_Twister
Anyway, both the Linear congruential generator and the mersenne twister algorithm rely on the first(seed) number that is given.
(214013 * seed + 2531011), for example will always calculate the exact same number when given the same seed.
If you reseed it with the same seed as you used last time, it will, again, calculate the same number.
If you don't reseed it will use the number it calculated as the new seed, resulting in randomly looking numbers.
+ 1
First, thanks a lot, I was able to make it work with your advice.
Second though, how does the generator work that it matters whether I use/call the same seed once or always upon call, when it is the same value that is used (according to your words, or do I mistake something here?)?
Would you mind explaining that a bit deeper, I always wondered how randomness, seeded one aswell, comes to work (sorry for stealing your time though).
0
Wow, thank you for all the material (and helping in general)!!!