Java: get a set of random numbers from a specified range

This is a method that accepts a range (max) and a number (n), returns an array of n random numbers.
n: size of random number array
max: largest available number (exclusive)

For example:
Input: n=5, max=100
Output: an array containing 5 random numbers whose range is from 0 to 99.

public static HashSet<Integer> getNRandom(int n, int max) {
	HashSet<Integer> set = new HashSet<Integer>();		
	Random random = new Random();
 
	while(set.size() <500){
		int thisOne = random.nextInt(max - 1);
		set.add(thisOne);
	}
 
	return set;
}

Random.nextInt(int n) returns a pseudo random number, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator’s sequence.

We can also specify the range like this:

public static HashSet<Integer> getNRandom(int n, int left, int right) {
	HashSet<Integer> set = new HashSet<Integer>();		
	Random random = new Random();
 
	while(set.size() <500){
		int thisOne = random.nextInt(right-left) + left;
		set.add(thisOne);
	}
 
	return set;
}

1 thought on “Java: get a set of random numbers from a specified range”

  1. in the inter loop, the condition indexRandomArr < n; should be indexRandomArr < j, because it is not necessary to check the elements after j as they have not been set yet.

Leave a Comment