How to randomly pick an element from an array

前端 未结 12 741
逝去的感伤
逝去的感伤 2020-11-22 16:48

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?

相关标签:
12条回答
  • 2020-11-22 17:06

    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)]; 
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:13
    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)]);
           }
    }
    
    0 讨论(0)
  • 2020-11-22 17:14

    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];
    
    0 讨论(0)
  • 2020-11-22 17:15

    Take a look at this question:

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

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

    myArray[myRandomNumber];
    
    0 讨论(0)
  • 2020-11-22 17:17
    public static int getRandom(int[] array) {
        int rnd = new Random().nextInt(array.length);
        return array[rnd];
    }
    
    0 讨论(0)
  • 2020-11-22 17:19

    Use the Random class:

    int getRandomNumber(int[] arr)
    {
      return arr[(new Random()).nextInt(arr.length)];
    }
    
    0 讨论(0)
提交回复
热议问题