How to randomly pick an element from an array

Java

Java Problem Overview


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 Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

With Java 7, one can use ThreadLocalRandom.

> A random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools.

public static int getRandomElement(int[] arr){
    return arr[ThreadLocalRandom.current().nextInt(arr.length)];
}

//Example Usage:
int[] nums = {1, 2, 3, 4};
int randNum = getRandomElement(nums);
System.out.println(randNum);

A generic version can also be written, but it will not work for primitive arrays.

public static <T> T getRandomElement(T[] arr){
   return arr[ThreadLocalRandom.current().nextInt(arr.length)];
}

//Example Usage:
String[] strs = {"aa", "bb", "cc"};
String randStr = getRandomElement(strs);
System.out.println(randStr);

Solution 5 - Java

Use the Random class:

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

Solution 6 - Java

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]

Solution 7 - Java

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)

Solution 8 - Java

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

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

Hope this helps!

Solution 9 - Java

Take a look at this question:

https://stackoverflow.com/questions/363681/java-generating-random-number-in-a-range

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

Solution 10 - Java

Since you have java 8, another solution is to use Stream 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.

 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.

Solution 11 - Java

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

Solution 12 - Java

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

Solution 13 - Java

package io.github.baijifeilong.tmp;

import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;

/**
 * Created by [email protected] at 2019/1/3 下午7:34
 */
public class Bar {
    public static void main(String[] args) {
        Stream.generate(() -> null).limit(10).forEach($ -> {
            System.out.println(new String[]{"hello", "world"}[ThreadLocalRandom.current().nextInt(2)]);
        });
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBreakHeadView Question on Stackoverflow
Solution 1 - JavaChris DennettView Answer on Stackoverflow
Solution 2 - JavaLuchian GrigoreView Answer on Stackoverflow
Solution 3 - JavaStephen OstermillerView Answer on Stackoverflow
Solution 4 - JavaUnmitigatedView Answer on Stackoverflow
Solution 5 - JavamoongoalView Answer on Stackoverflow
Solution 6 - JavaJames.XuView Answer on Stackoverflow
Solution 7 - Javaratchet freakView Answer on Stackoverflow
Solution 8 - JavadecdenView Answer on Stackoverflow
Solution 9 - JavaBrian DiCasaView Answer on Stackoverflow
Solution 10 - JavaJohnny WillerView Answer on Stackoverflow
Solution 11 - Javauser6022884View Answer on Stackoverflow
Solution 12 - JavaRavi SapariyaView Answer on Stackoverflow
Solution 13 - JavaBaiJiFeiLongView Answer on Stackoverflow