简体   繁体   English

Java:随机setSeed

[英]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 . 因此,我需要使用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. 问题是我必须在我的代码中传递/获取r这个实例。

I would like to know if there is solution close to C: 我想知道是否有接近C的解决方案:

Math.Random(currentSeed);

The closest 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? 有任何想法吗?

是的,您需要通过参数或通过全局变量(静态变量或单例)传递相同的Random实例。

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 eg if its multi-threaded you will get a different result. 如果您的类以不同的顺序执行(例如,如果它是多线程的),您将得到不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM