gpt4 book ai didi

java - Collections.shuffle 只工作一次

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:48:11 25 4
gpt4 key购买 nike

我检查了以前的答案,但它对我不起作用。

我有以下代码

public static void createPopulation(ArrayList<City> city)
{
for (int i = 0; i<gen.getSize(); i++) {
ArrayList<City> copy = new ArrayList<City> (city); //added from previous question
Collections.shuffle(copy, new Random(seed));
gen.add(copy);
}
}

它会随机播放一次,无论是否带有评论行,但不会再次随机播放。这是一个 GP 算法(好吧,它的开始),我必须在其中洗牌人口的成员。

最佳答案

那是因为您重新创建了 Random 对象。

这样做:

Random r = new Random(seed);
for (int i = 0; i<gen.getSize(); i++) {
ArrayList<City> copy = new ArrayList<City> (city); //added from previous question
Collections.shuffle(copy, r);
gen.add(copy);
}

来自 the javadoc :

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

Random 的一个实例是一个生成器,每次调用随机函数时其状态都会改变。在这里您不想将此状态重置为基于初始种子的状态,因为这会导致相同的返回数字序列。这就是为什么您不想为每次改组重新创建一个新实例。

关于java - Collections.shuffle 只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15878559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com