I want to randomly select an integer among n numbers, where n is small (say 5). To do this, I am using std::uniform_int_distribution
.
The exact details of the distribution are not that important, but I want the results to be random and to use all the integers in the range. The randomized selection will be done many more times that the length (size) of the range. I want to the choice to be done quickly and randomly.
But, no matter how many times I run it, I receive the same output. In an attempt to get different output, I let some minutes to pass and then tried again: the result was still the same (probably this code is not affected by time).
Is it expected that each time I use uniform_int_distribution
that I will get the same output?
As uniform_int_distribution
in particular is not what I need (I just need random numbers), I tried with RandomUniform from my pseudosite. While I got different results than std::uniform_int_distribution
produced, when I ran it again it produced the same numbers each time. Of course, I used the same main.
I didn't post RandomUniform, in order to not make the post any bigger.
As others have mentioned, your main problem is that you're not seeding your engine. I thought I'd address something else since you note that speed and quality is important to you.
Unlike other engines,
default_random_engine
makes no guarantees. Do not use it if you have any reasonable requirement. It's only there if you don't know what you're doing and the application of it doesn't really matter. From the standard:A better choice might be
mt19937
, which has high quality and is very fast.As said, I should seed the generator. Notice that the reference does not provide something obvious for a seed.
The working code is here.
Notice, that as mentioned in the answers,
mt19937
should be used, for better speed and quality.Example in first answer here.
Here is another example, found on the internet, that compiles.
You didn't seed your
default_random_engine
, so it's using the default, constant, seed.Try to seed the random engine. Time is a good choice. Read this to get familiar to another ways.
or you can use
std::random_device
which tries to produce non-deterministic random numbersIt uses a hardware random generator device or generates a pseudo random number. Useful to seed.