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?
In a column, use =RAND() formula to generate a set of random numbers between 0 and 1.
Random random = new Random(); int rand15Digt = random. nextInt(15);
Random numbers in Java can be generated using either java. util. Random , ThreadLocalRandom class or by using Math. random() method.
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));
}
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With