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

Suppose I have an array / vector of numbers, for example, 1,3,7,9, then I need to guess the number from this list randomly. Using the Random class in Java seems impossible. Can anyone kindly help me tell me how to do this. I need to change the list of numbers used to generate random numbers. I am trying to implement a strategy to play a game with a battleship automatically as a task. Please help me do this?

+3
source share
3 answers

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

+4
source

If you just want to select only one random number or want to select several random numbers with reloading (i.e. allow the possibility to select the same number several times), you can create a random index:

List<Integer> lst = ....; int index = new Random().nextInt(lst.size()); Integer randomeValue = lst.get(index); 

You can use an array instead. Each selection requires O(1) .

If you need to select several different random numbers from a list, then using Collections.shuffle() and repeating in the list would be the best solution. This requires O(n) for all queries.

+18
source

I am with tordek on this: Doesn't shuffling look like a pretty hard way to pick a configured number of random numbers from the original vector?

Wouldn't it be easier to just accept the msaeed sentence on how to choose one random number and repeat it n times? Perhaps collect your random values ​​as a set and keep choosing until the size of your set is large enough ... (do not forget some kind of check for the boundary condition when there are not enough numbers in the original vector to supply the set number of random values)

0
source

All Articles