Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate set of unique random numbers in Java

Tags:

java

I want to create 10 random numbers in the range 0-500. But the problem is that I want those numbers to be unique. For 2 random numbers i could create something as the following:

int randomItem1 = r.nextInt(500);
int randomItem2 = r.nextInt(500);
while(randomItem1==randomItem2){
    randomItem1=randomItem();
    randomItem2=randomItem();
}

But if I do this for 10, I think that the while it will stack. And I'm saying this because I'm trying to create a huge algorithm which is trying to make continuous evaluations and i want continously to take 10 random and unique numbers. I don't know what to do. Any ideas or suggestions?

like image 485
Alex Mellon Avatar asked Feb 24 '12 00:02

Alex Mellon


People also ask

How do you generate a unique random number?

In a column, use =RAND() formula to generate a set of random numbers between 0 and 1.

How do you generate a 15 digit unique random number in Java?

Random random = new Random(); int rand15Digt = random. nextInt(15);

How do you generate multiple random numbers in Java?

Random numbers in Java can be generated using either java. util. Random , ThreadLocalRandom class or by using Math. random() method.


2 Answers

Looks like you are storing these in individual variables. The "normal" place to store groups of items like this would usually be in a list or array.

In this case, store them in a "set" data structure instead. It will not allow duplicates.

Set documentation: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html

Set set = new HashSet();

while (set.size() < 10) {
    set.add(r.nextInt(500));
}
like image 162
Chris Dutrow Avatar answered Sep 23 '22 06:09

Chris Dutrow


Java Collections has a shuffle method. You can put your numbers into an ArrayList and then shuffle its content. If the ArrayList contains n numbers, calling the shuffle method, would give you the same ArrayList containing n numbers but arranged randomly.

for(int i=0;i<10;i++){
list.add(i);  // list contains: [0,1,2,3,4,5,6,7,8,9]
}
Collections.shuffle(list);// list now contains: [0, 9, 3, 1, 5, 8, 7, 2, 6, 4]
like image 27
Muhammad Asaduzzaman Avatar answered Sep 22 '22 06:09

Muhammad Asaduzzaman