How to generate a random number with Java from given list of numbers

青春壹個敷衍的年華 提交于 2020-01-11 03:35:06

问题


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:


Put the numbers in an ArrayList and use Collections.shuffle(arrayList);




回答2:


If you just want to select one random 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.

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.




回答3:


I'm with tordek on this one: Doesn't shuffling seem like a fairly heavy-weight way to select a configured number of random numbers from a source vector?

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)



来源:https://stackoverflow.com/questions/1247915/how-to-generate-a-random-number-with-java-from-given-list-of-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!