JAVA : Selected Random Numbers Between Range and No Duplicate

JAVA 7 introduced new package java.util.Random for handle random numbers. previously we used Math.random() to get random numbers.

In below example generating selected random numbers of certain integers range with out duplicate. Here range belongs to Min=0 , Max=25 and need non duplicate numbers 8.

Pre-Requisite

  • JAVA 7/JAVA 8

Sample Code

package random;

import java.util.ArrayList;
import java.util.Random;

public class SelectedRandomNumberBetweenRangeNoDuplicate {

	public static void main(String[] args) {

		 //Select Eight random number without duplicate between 0 and 50
		 ArrayList list = getRandomNonRepeatingIntegers(8, 0, 25);
		    for (int i = 0; i < list.size(); i++) {
		        System.out.println("" + list.get(i));
		    }
	}

	//Get selected size number without duplicate
	public static ArrayList getRandomNonRepeatingIntegers(int size, int min,
	        int max) {
	    ArrayList numbers = new ArrayList();
	    Random random = new Random();
	    while (numbers.size() < size) {
	    	//Get Random numbers between range
	        int randomNumber = random.nextInt((max - min) + 1) + min;
            //Check for duplicate values
	        if (!numbers.contains(randomNumber)) {
	            numbers.add(randomNumber);
	        }
	    }

	    return numbers;
	}

}

Output


4
19
20
22
17
13
8
16

Summary

I above code explain about How to generate random numbers and avoid duplicate of numbers between certain range.

Advertisements

This site uses Akismet to reduce spam. Learn how your comment data is processed.