Generation of the same sequence of random numbers

后端 未结 5 1856
广开言路
广开言路 2021-01-07 20:42

I want to generate random numbers in java, I know I should use existing methods like Math.random(), however, my question is: how can I generate the same sequence of numbers,

5条回答
  •  执笔经年
    2021-01-07 21:22

    Sure - just create an instance of Random instead of using Math.random(), and always specify the same seed:

    Random random = new Random(10000); // Or whatever seed - maybe configurable
    int diceRoll = random.nextInt(6) + 1; // etc
    

    Note that it becomes harder if your application has multiple threads involved, as the timing becomes less predictable.

    This takes advantage of Random being a pseudo-random number generator - in other words, each time you ask it for a new result, it manipulates internal state to give you a random-looking sequence, but knowing the seed (or indeed the current internal state) it's entirely predictable.

提交回复
热议问题