还记得随机种子中的位置吗?

时间:2020-01-17 19:09:41

标签: java random

首先,我主要是自学成才,所以如果我不知道正确的术语或犯了一些菜鸟错误,请原谅我。

所以,我正在用种子制作一个Random变量。当您从变量中获取“下一个”时,它将从该种子中获取下一个值。有什么方法可以用随机变量记录您的位置?例如,理想情况下,以下代码将输出两个相同的字符串:

//My attempt to save my location in a Random:

r = new Random(5);

for (int i = 0; i < 10; i++) {
    System.out.print(r.nextInt(2));
    if (i == 9) {
        System.out.print(" ");
    }
}

//====================================

System.out.println("\n-------------");
r = new Random(5);
for (int i = 0; i < 5; i++) {
    System.out.print(r.nextInt(2));
}

r = new Random(r.nextLong());
System.out.print(" ");
for (int i = 0; i < 5; i++) {
    System.out.print(r.nextInt(2));
}

但返回:

1001010100 1100110011
-------------
1001010100 0010010111
-------------

是否有某种方法可以“记住”我的位置,以便我可以创建一个新的Random变量,该变量将在上一个变量退出的地方继续?最好是,我宁愿不序列化该变量-这不是世界末日,但我想知道是否还有其他方法。

1 个答案:

答案 0 :(得分:2)

您无法使用一个种子生成getOfficialScenarios() { this.$axios .get('scenariolog') .then(response => { this.officialScenarios = response.data; }) .catch(error => { this.errors.push(error); }); } 数字,然后使用其他种子从上一个序列中断的地方开始。

您可以再次使用同一种子,并使用流并跳过之前生成的数字。

第一个列表的后5个值应等于下一个列表的前5个值。

n

您也可以继续使用相同的 Random r = new Random(23); r.ints(10,1,100).forEach(a->System.out.print(a + " " )); System.out.println(); r = new Random(23); r.ints(10,1,100).skip(5).forEach(a->System.out.print(a + " ")); 实例,因为它们不会过期。

Random

当然,如果您想长时间保留同一对象,或者要生成大量随机值并进行跟踪,那么序列化可能是最好的解决方案。