saplingPro
saplingPro

Reputation: 21329

Generating a random number from the array

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

Answers (4)

TAAPSogeking
TAAPSogeking

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

Achintya Jha
Achintya Jha

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

Sano
Sano

Reputation: 108

try this

    import java.util.Random;

    Random random = new Random();
    System.out.println(arr[random.nextInt(arr.length)]);

Upvotes: 6

Matei Suica
Matei Suica

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

Related Questions