Could someone tell me how can I pick several different random numbers from an array at one time?
For example, there is a long int array. I want to pick 7 numbers from it. All the numbers mustn’t be the same and sort them by increase sequence.
Random random = new Random();
int a = mixColor[random.nextInt(mixColor.length)];
int b = mixCoor[random.nextInt(mixCoor.length)];
int c = mixCoor[random.nextInt(mixCoor.length)];
int d = mixCoor[random.nextInt(mixCoor.length)];
int e = mixCoor[random.nextInt(mixCoor.length)];
while(b!=c && c!=d && b!=d) {
b = mixCoor[random.nextInt(mixCoor.length)];
c = mixCoor[random.nextInt(mixCoor.length)];
d = mixCoor[random.nextInt(mixCoor.length)];
}
mixColor[] and mixCoor[] are long int arrays. I can do in this way, but if I want to pick more numbers this will be really complicated. And I need to sort them as well. Someone get good ideas?
Try with this method:
Use it like this:
The method guarantees that exactly
nelements are picked at random, and that they will be returned sorted. It also guarantees that no element will be picked more than once, and the resulting array won’t have duplicates, as long as the input array is duplicate-free.The above code works fine, but it’s cumbersome having to switch back and forth between
intandInteger, and it might be slow if the input array is big (say, > 100.000 elements). Test it first, and see if it fits your needs.