如何从给定的数字列表中使用 Java 生成随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1247915/
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
How to generate a random number with Java from given list of numbers
提问by Tharindu Madushanka
Assume I have an array/vector of numbers like 1,3,7,9 then I need to guess a number from this list randomly. Using Random class in Java it seems like not possible to do this. Could anyone kindly help me to tell a way to do this kind of thing. I have to change the list of numbers used to generate random number. I am trying to implement a strategy to play battleship game automatically as an assignment. Kindly help me to do this ?
假设我有一个像 1,3,7,9 这样的数字数组/向量,那么我需要从这个列表中随机猜测一个数字。在 Java 中使用 Random 类似乎不可能做到这一点。任何人都可以帮助我告诉做这种事情的方法。我必须更改用于生成随机数的数字列表。我正在尝试实施一种策略来自动玩战舰游戏作为一项任务。请帮我做这个?
回答by notnoop
If you just want to select onerandom number only, or want to select multiple random numbers with reinsertion (i.e. allow possibility of selecting the same number multiple times), you can generate a random index:
如果您只想选择一个随机数,或者想选择多个随机数并重新插入(即允许多次选择相同的数字),您可以生成一个随机索引:
List<Integer> lst = ....;
int index = new Random().nextInt(lst.size());
Integer randomeValue = lst.get(index);
You can use an array instead as well. This requires O(1)for each selection.
您也可以使用数组代替。这需要O(1)每个选择。
If you need to select multiple distinct random numbers from the list, then using Collections.shuffle()and iterating through the list would be a better solution. This requires O(n)for all the queries.
如果您需要从列表中选择多个不同的随机数,那么使用Collections.shuffle()并迭代列表将是一个更好的解决方案。这需要O(n)所有查询。
回答by Charles Ma
Put the numbers in an ArrayList and use Collections.shuffle(arrayList);
将数字放入 ArrayList 并使用Collections.shuffle(arrayList);
回答by CPerkins
I'm with tordekon this one: Doesn't shuffling seem like a fairly heavy-weight way to select a configured number of random numbers from a source vector?
我在这个问题上与tordek在一起:从源向量中选择配置数量的随机数似乎不是一种相当重量级的方法吗?
Wouldn't it be faster to just take msaeed's suggestion for how to pick one random number, and repeat it n times? Perhaps assemble your random values as a Set, and keep selecting until your set size is big enough... (don't forget some kind of a check for the edge condition where there's insufficient numbers in the source vector to supply the configured number of random values)
只接受msaeed关于如何选择一个随机数的建议并重复 n 次不是更快吗?也许将您的随机值组合为一个集合,并继续选择直到您的集合大小足够大......(不要忘记对源向量中没有足够数字来提供配置数量的边缘条件进行某种检查随机值)

