如何从数组中随机选择一个元素

时间:2021-05-10 16:00:58

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?

例如,我有一个新的int[]{1,2,3}数组,我如何随机选择一个数字?

11 个解决方案

#1


109  

public static int getRandom(int[] array) {
    int rnd = new Random().nextInt(array.length);
    return array[rnd];
}

#2


10  

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];

#3


6  

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.

如果您正在选择需要不可预测的随机数组元素,那么应该使用java.security。SecureRandom而不是随机的。这就确保了如果有人知道最后几个选择,他们就不会有猜测下一个的优势。

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

如果您希望使用泛型从对象数组中选择一个随机数,您可以为此定义一个方法(字符串数组中随机元素的源Avinash R):

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)]; 
    }
}

#4


3  

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]

使用java.util。随机生成0到数组长度的随机数:random_number,然后使用随机数获得整数:array[random_number]

#5


2  

Use the Random class:

使用随机类:

int getRandomNumber(int[] arr)
{
  return arr[(new Random()).nextInt(arr.length)];
}

#6


1  

Since you have java 8, another solution is to use Stream API.

因为您有java 8,另一个解决方案是使用流API。

new Random().ints(1, 500).limit(500).forEach(p -> System.out.println(list[p]));

Where 1 is the lowest int generated (inclusive) and 500 is the highest (exclusive). limit means that your stream will have a length of 500.

其中1是生成的最小整数(包括),500是最高的整数(排除)。限制意味着您的流将有500的长度。

 int[] list = new int[] {1,2,3,4,5,6};
 new Random().ints(0, list.length).limit(10).forEach(p -> System.out.println(list[p])); 

Random is from java.util package.

随机从java。util包。

#7


1  

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)

Math.random()返回一个从0.0(包括)到1.0(排他性的)之间的double

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

乘以这个数组。长度在0.0(包括)和数组之间提供了一个双重值。长度(独家)

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

转换为int将会四舍五入,得到0(包括)和数组之间的整数。长度是1(包容)

#8


0  

Take a look at this question:

看看这个问题:

How do I generate random integers within a specific range in Java?

如何在Java的特定范围内生成随机整数?

You will want to generate a random number from 0 to your integers length - 1. Then simply get your int from your array:

你需要从0到整数长度- 1生成一个随机数。然后从数组中获取int:

myArray[myRandomNumber];

#9


0  

Java has a Random class in the java.util package. Using it you can do the following:

Java中有一个随机类。util包。使用它你可以做以下事情:

Random rnd = new Random();
int randomNumberFromArray = array[rnd.nextInt(3)];

Hope this helps!

希望这可以帮助!

#10


0  

package workouts;

import java.util.Random;

/**
 *
 * @author Muthu
 */
public class RandomGenerator {
    public static void main(String[] args) {
     for(int i=0;i<5;i++){
         rndFunc();
     } 
    }
     public static void rndFunc(){
           int[]a= new int[]{1,2,3};
           Random rnd= new Random();
           System.out.println(a[rnd.nextInt(a.length)]);
       }
}

#11


-1  

You can also try this approach..

你也可以试试这种方法。

public static <E> E[] pickRandom_(int n,E ...item) {
        List<E> copy = Arrays.asList(item);
        Collections.shuffle(copy);
        if (copy.size() > n) {
            return (E[]) copy.subList(0, n).toArray();
        } else {
            return (E[]) copy.toArray();
        }

    }

#1


109  

public static int getRandom(int[] array) {
    int rnd = new Random().nextInt(array.length);
    return array[rnd];
}

#2


10  

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];

#3


6  

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.

如果您正在选择需要不可预测的随机数组元素,那么应该使用java.security。SecureRandom而不是随机的。这就确保了如果有人知道最后几个选择,他们就不会有猜测下一个的优势。

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

如果您希望使用泛型从对象数组中选择一个随机数,您可以为此定义一个方法(字符串数组中随机元素的源Avinash R):

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)]; 
    }
}

#4


3  

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]

使用java.util。随机生成0到数组长度的随机数:random_number,然后使用随机数获得整数:array[random_number]

#5


2  

Use the Random class:

使用随机类:

int getRandomNumber(int[] arr)
{
  return arr[(new Random()).nextInt(arr.length)];
}

#6


1  

Since you have java 8, another solution is to use Stream API.

因为您有java 8,另一个解决方案是使用流API。

new Random().ints(1, 500).limit(500).forEach(p -> System.out.println(list[p]));

Where 1 is the lowest int generated (inclusive) and 500 is the highest (exclusive). limit means that your stream will have a length of 500.

其中1是生成的最小整数(包括),500是最高的整数(排除)。限制意味着您的流将有500的长度。

 int[] list = new int[] {1,2,3,4,5,6};
 new Random().ints(0, list.length).limit(10).forEach(p -> System.out.println(list[p])); 

Random is from java.util package.

随机从java。util包。

#7


1  

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)

Math.random()返回一个从0.0(包括)到1.0(排他性的)之间的double

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

乘以这个数组。长度在0.0(包括)和数组之间提供了一个双重值。长度(独家)

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

转换为int将会四舍五入,得到0(包括)和数组之间的整数。长度是1(包容)

#8


0  

Take a look at this question:

看看这个问题:

How do I generate random integers within a specific range in Java?

如何在Java的特定范围内生成随机整数?

You will want to generate a random number from 0 to your integers length - 1. Then simply get your int from your array:

你需要从0到整数长度- 1生成一个随机数。然后从数组中获取int:

myArray[myRandomNumber];

#9


0  

Java has a Random class in the java.util package. Using it you can do the following:

Java中有一个随机类。util包。使用它你可以做以下事情:

Random rnd = new Random();
int randomNumberFromArray = array[rnd.nextInt(3)];

Hope this helps!

希望这可以帮助!

#10


0  

package workouts;

import java.util.Random;

/**
 *
 * @author Muthu
 */
public class RandomGenerator {
    public static void main(String[] args) {
     for(int i=0;i<5;i++){
         rndFunc();
     } 
    }
     public static void rndFunc(){
           int[]a= new int[]{1,2,3};
           Random rnd= new Random();
           System.out.println(a[rnd.nextInt(a.length)]);
       }
}

#11


-1  

You can also try this approach..

你也可以试试这种方法。

public static <E> E[] pickRandom_(int n,E ...item) {
        List<E> copy = Arrays.asList(item);
        Collections.shuffle(copy);
        if (copy.size() > n) {
            return (E[]) copy.subList(0, n).toArray();
        } else {
            return (E[]) copy.toArray();
        }

    }