开发者

Java : Random setSeed

I'm having a small conceptual problem.

I need to seed my random so that I always get the same radom when I reload my levels.

So therefore I need to use Random#setSeed.

The problem I have then is that I then need to do a

Random r = new Random();
r.setSeed(currentSeed);

The problem is that I have then have to pass/fetch this instance of r across my code.

I would like to know if there is solution close to C:

Math.Random(currentSeed);

The closes开发者_如何学Got I have now is:

ClassA:
  public static Random r;
  private int currentSeed = ...;
  initRandom(){
    r = new Radom(currentSeed);
  }

ClassB:
  ...
  //instead of Math.random();
  r.random();
  ...

But that doesn't seem very nice.

Any ideas?


Yes, you need to pass the same Random instance around, either as a parameter, or by mean of a global (static variable or singleton).


If you are using the same random across classes and you want reproduce-ability, you need to ensure that it is used in the same order as well. If your classes execute in a different order e.g. if its multi-threaded you will get a different result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜