I am looking for solution to pick number randomly from an integer array.
For example I have an array new int[]{1,2,3}
, how can I pick a number randomly?
I am looking for solution to pick number randomly from an integer array.
For example I have an array new int[]{1,2,3}
, how can I pick a number randomly?
use
java.util.Random
to generate a random number between 0 and array length:random_number
, and then use the random number to get the integer:array[random_number]
You can also use
Math.random()
returns andouble
between0.0
(inclusive) to1.0
(exclusive)Multiplying this with
array.length
gives you adouble
between0.0
(inclusive) andarray.length
(exclusive)Casting to
int
will round down giving you and integer between0
(inclusive) andarray.length-1
(inclusive)If you are going to be getting a random element multiple times, you want to make sure your random number generator is initialized only once.
If you are picking random array elements that need to be unpredictable, you should use java.security.SecureRandom rather than Random. That ensures that if somebody knows the last few picks, they won't have an advantage in guessing the next one.
If you are looking to pick a random number from an Object array using generics, you could define a method for doing so (Source Avinash R in Random element from string array):
You can use the Random generator to generate a random index and return the element at that index: