Does the random object always contains a seed, even when not given one? And if so is it possible to get
this seed?
Motivation: I want my program to be random but i want to be able to reproduce it whenever i want. What i currently do is generate a random number, store it and put it as seed into another Random object that i use for the actual program. This way i can look up the generated seed if i want to reproduce anything.
I would like to know this for Java
and C#
since these are my main languages and this question struck me a couple times working in both languages.
Seed will be generated for you implicitly if you don't provide the random constructor with one. To set a seed and use it again at some other point in code or reproduce anything, try this:
long seed = System.currentTimeMillis();
Random rand = new Random(seed);
System.out.println(seed);
To answer your first question from a C# perspective just take a look at the documentation - MSDN. For the Random
classes parameterless constructor it says:
Initializes a new instance of the Random class, using a time-dependent default seed value
So yes, if you don't supply a seed the runtime will use a default one.
Again, looking at the documentation you can see you can't find the seed used if you don't supply it.
As for wanting to be able to consistently produce random numbers, you could create an IRandomNumberGenerator
interface and create 2 implementations. One would make calls to the Random
class, the other could be used for testing purposes and would simply return whatever you wish. Then you could use dependency injection to control which implementation is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With