How to randomly pick an element from an array

2019-01-01 05:31发布

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?

标签: java
11条回答
忆尘夕之涩
2楼-- · 2019-01-01 06:19

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]

查看更多
浪荡孟婆
3楼-- · 2019-01-01 06:21

You can also use

public static int getRandom(int[] array) {
    int rnd = (int)(Math.random()*array.length);
    return array[rnd];
}

Math.random() returns an double between 0.0 (inclusive) to 1.0 (exclusive)

Multiplying this with array.length gives you a double between 0.0 (inclusive) and array.length (exclusive)

Casting to int will round down giving you and integer between 0 (inclusive) and array.length-1 (inclusive)

查看更多
明月照影归
4楼-- · 2019-01-01 06:22

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.

import java.util.Random;

public class RandArray {
    private int[] items = new int[]{1,2,3};

    private Random rand = new Random();

    public int getRandArrayElement(){
        return items[rand.nextInt(items.length)];
    }
}

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):

import java.util.Random;

public class RandArray {
    private static Random rand = new Random();

    private static <T> T randomFrom(T... items) { 
         return items[rand.nextInt(items.length)]; 
    }
}
查看更多
谁念西风独自凉
5楼-- · 2019-01-01 06:23

You can use the Random generator to generate a random index and return the element at that index:

//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];
查看更多
ら面具成の殇う
6楼-- · 2019-01-01 06:33
public static int getRandom(int[] array) {
    int rnd = new Random().nextInt(array.length);
    return array[rnd];
}
查看更多
登录 后发表回答