How to save the state of a Random generator in C#?

前端 未结 6 653
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 10:29

For testing purposes I\'m creating random numbers with a given seed (i.e. not based on the current time).

Thus the whole program is deterministic.

If someth

6条回答
  •  北海茫月
    2020-11-30 11:05

    Store the amount of times the random number generator ran like Xi Huan wrote.

    Then simply loop to restore the old state.

    Random rand= new Random();
    int oldRNGState = 439394;
    
    for(int i = 1; i < oldRNGState-1; i++) {
        rand.Next(1)
    }
    

    Now just do

    int lastOldRNGValue = rand.Next(whateverValue);
    

    There is no way around this you have to loop to get back to where you left off.

提交回复
热议问题