Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get seed of Random object without passing in the seed?

Tags:

java

c#

random

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.

like image 575
Madmenyo Avatar asked Mar 20 '23 08:03

Madmenyo


2 Answers

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);
like image 157
Jeeshu Mittal Avatar answered Mar 21 '23 21:03

Jeeshu Mittal


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.

like image 37
Daniel Kelley Avatar answered Mar 21 '23 21:03

Daniel Kelley