So i want to get random elements of a list with uniform distribution in Java. I know that in the Random class, for example the nextInt method, already give me something like that:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
So given something like the code below:
Random rnd = new Random();
int numTimes = 10;
for(int i = 0; i < numTimes*n; i++){
System.out.println(rnd.nextInt(10));
}
I expect that for small "n" I can't quite see a good uniform distribution, probably increasing it, I will see something better. So my question is, how can I guarantee a uniform distribution within smaller n, or in other words, with "n = 2" how can I get every number at least once?
Trying to explain better: giving 10-number range dataset, and for example 20 iterations, is there a way that each number is printed 1-3 times, in other words, at least once?
If you want to generate numbers that occur exactly the same number of times (which is not the same as a uniform distribution), then there is a better way to do it.
int n = 2; // your "n"
int t = 100; // how often you want each number x to occur, where 0 <= x < n
// Build a list of numbers
List<Integer> l = new ArrayList<>();
for (int i = 0; i < t; i++) {
for (int j = 0; j < n; j++) {
l.add(j);
}
}
// Shuffle the list randomly; this ensures the order is random but each number x occurs
// as often as any other x
Collections.shuffle(l);
for (Integer value : l) {
System.out.println(value);
}
If you want to have some numbers at least once, but don't care about the others; then insert 1 of each number that you want at least once and the rest randomly. If I understand you correctly, you want the numbers 1, 2 and 3 at least once, and then randomly numbers 1, 2 and 3. So, that would be:
int n = 3; // your "n"
// Build a list of numbers
List<Integer> l = new ArrayList<>();
for (int x = 1; x <= n; x++) {
l.add(x);
}
int t = 17; // add 17 more random numbers in range 1-3 inclusive
for (int i = 0; i < t; i++) {
l.add(rnd.nextInt(n) + 1);
}
// Shuffle
Collections.shuffle(l);
// Print
for (Integer value : l) {
System.out.println(value);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments