Generating Unique Random Number Upto A Limit In Java
Here we will try to figure out a way to generate unique random number within a upper limit .
The problem with general random number generation is there is a chance of collision but we want to return unique random numbers each time a client call us , this is one of the solution which is easy to understand .
import java.util.*;
public class GenerateRandom {
public static int MAX = 100;
Set<Integer> numberSet = new HashSet<>();
public Integer generateRandomNumber(){
Random random = new Random();
if(numberSet.size() == 100){
return -1;
}
else{
int temp = random.nextInt(MAX) ;
while(numberSet.contains(temp)){
temp = random.nextInt(MAX);
}
numberSet.add(temp);
return temp;
}
}
}
here , we are maintaining a hash set of the numbers we have generated and checking each time for the generated number if it is present in the set or not , and we keep on doing it till we get the unique number .
here , we have implemented with a upper limit of 100 .
P.S :- There is a drawback to this method as there will be less numbers left , there will be more collisions , hence high response time .
I will update with a better algorithm to do so.