确定性地设置种子以在 Java 中随机播放 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6284589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:12:09  来源:igfitidea点击:

Setting a seed to shuffle ArrayList in Java deterministically

javarandom

提问by Ben Flynn

I have a list of integers (currently using cern.colt.list.IntArrayList). I can call "shuffle()" and randomly shuffle them. I would like to be able to reproduce a shuffle. I can reproduce a series of random numbers by setting a seed. I do not seem to be able to set a seed in this case. What should I do? I am open to other implementations.

我有一个整数列表(目前使用cern.colt.list.IntArrayList)。我可以调用“shuffle()”并随机对它们进行洗牌。我希望能够重现洗牌。我可以通过设置种子来重现一系列随机数。在这种情况下,我似乎无法设置种子。我该怎么办?我对其他实现持开放态度。

回答by aioobe

This is possible by using the shuffle method that allows you to provide the backing Randominstance: Collections.shuffle(List<?> list, Random rnd):

这可以通过使用 shuffle 方法来实现,该方法允许您提供支持Random实例Collections.shuffle(List<?> list, Random rnd)::

Example:

例子:

Collections.shuffle(yourList, new Random(somePredefinedSeed));

回答by CoolBeans

You can specify the Random instance with a seed value using public static void shuffle(List list, Random rnd). For the Random(long seed)constructor you can specify a seed.

您可以使用public static void shuffle(List list, Random rnd)指定带有种子值的 Random 实例。对于Random(long seed)构造函数,您可以指定一个种子。

From Java Docs:

来自 Java 文档:

Randomly permute the specified list using the specified source of randomness. All permutations occur with equal likelihood assuming that the source of randomness is fair.

使用指定的随机源随机排列指定的列表。假设随机源是公平的,所有排列都以相同的可能性发生。