Вопрос

Using a seed you can get a Random object to spit the same sequence of numbers over and over again. But what if you want to shut down your app, relaunch it and continue spitting numbers from where you left off? Simply initiating a new Random with the same seed starts the sequence again.

So.. Apart from maintaining a list of all calls made to Random and then re-calling them to get back to the same position, is there a better way?

edit: Zim-Zam has pointed out using Java Serialization to reinitiate the object but I don't want to add a single Java object to my save files which are otherwise entirely XML.

Это было полезно?

Решение 2

Okay. I believe I've found a solution that has stood up to a few tests.

Extending Random gives you access to the protected method next(int). Using this steps the Random position. So by overriding the nextFloat/nextInt/etc methods and incrementing a counter. I can initiate a new Random object, using the same seed and a count and called next() enough times to catch up to the previous instance. Seems to work well and is a nice simple solution.

Thanks to those who answered/commented.

Другие советы

You can serialize your Random object with ObjectOutputStream to save its state; when you start your program again, deserialize it with ObjectInputStream and your Random will start where it left off.

Alternatively, copy-paste the Java Random source code into your own MyRandom generator; this will give you a access to the internal workings of the generator so that you can save and restore its state.

Or if you don't fancy either serialisation or overriding a fairly complex class, why not:

Random mySaveableRandom = new Random();

long bookmark() {
    long bookmark = mySaveableRandom.nextLong();
    mySaveableRandom.setSeed(bookmark);
    return bookmark;
}
...
void startFrom(long bookmark) {
    mySaveableRandom.setSeed(bookmark);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top