How can I get the seed from a Random already created

早过忘川 提交于 2021-02-07 23:15:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!