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?
Random numbers in Java can be generated using either java. util. Random , ThreadLocalRandom class or by using Math. random() method.
Random random = new Random(); int rand15Digt = random. nextInt(15);
For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);
Try with this method:
public static int[] pickNRandom(int[] array, int n) {
List<Integer> list = new ArrayList<Integer>(array.length);
for (int i : array)
list.add(i);
Collections.shuffle(list);
int[] answer = new int[n];
for (int i = 0; i < n; i++)
answer[i] = list.get(i);
Arrays.sort(answer);
return answer;
}
Use it like this:
int[] mixColor = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int[] randomPicks = pickNRandom(mixColor, 5);
The method guarantees that exactly n
elements 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 int
and Integer
, 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.
Random gen = new Random();
int max = mixCoor.length; // Maximum Random value to generate
ArrayList<Integer> picked = new ArrayList<Integer>(); // List of picked numbers
for(int i = 0; i < numToBePicked; i++) {
int index = gen.nextInt(max);
if(!picked.contains(mixCoor[index]) // If the number isn't already picked
picked.add(mixCoor[index]); // Add it to the "picked" list
}
Collections.sort(picked); // Sort the picked numbers into ascending order
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