问题
I have to be able to repeat an experiment made with my code, it makes a few random numbers and I need to get the initialization value of my new random() sentence. I have this sentence to make the random object I use
Dim r As Random = New Random()
As I have read it gets the initialization value from system datetime. If the experiment were successfull I'd needed to be able to repeat it. How could I get the initialization number to be able to do:
Dim r As Random = New Random(OldInitializationValue)
I think I'll have to make a Initialization value myself each time I execute my app but If there were a method to save it I'd be glad to know it.
Thank you in advance for your answers.
回答1:
Random
does not expose the initial seed, it doesn't even store it so there is no way to retrieve it. So you have to use the constructor that takes the seed and store it yourself.
Dim mySeed As Int32 = Environment.TickCount ' store it somewhere '
Dim myRandom = New Random(mySeed)
For i As Int32 = 1 To 10
Console.WriteLine(myRandom.Next(1, 100))
Next
' somehwere else
myRandom = New Random(mySeed)
For i As Int32 = 1 To 10
Console.WriteLine(myRandom.Next(1, 100))
Next
Now you can always create a random instance with the same seed to get the same sequence of pseudo random values.
来源:https://stackoverflow.com/questions/36030374/how-can-i-get-the-seed-from-a-random-already-created