Reputation: 21329
Suppose there is an array :
int arr[] = {0,1,2}
Is there a way I can generate a random number out of 0,1,2
(i.e from the array) ?
Upvotes: 0
Views: 356
Reputation: 360
This will pick a number randomly out of the array.
public static void main(String[] args)
{
int arr[] = {0,1,2};
System.out.println(arr[(int)(Math.random()*arr.length)]);
}
Upvotes: 0
Reputation: 12843
If you want unique element each time from the array then try this:
Integer arr[] = {0,1,2}
Collections.shuffle(Arrays.asList(arr));
for(int unique: ar)
System.out.println(unique);
Shuffle method of Collections will randomly shuffle the given array .
Upvotes: 1
Reputation: 108
try this
import java.util.Random;
Random random = new Random();
System.out.println(arr[random.nextInt(arr.length)]);
Upvotes: 6
Reputation: 859
Sure. You should generate a number between 0 and arr.length-1, round it to a int number and then take the arr[your_random_number] element.
int random_index = (int) round(Math.random() * (arr.length - 1));
then your element would be arr[random_index]
Upvotes: 2