import java.util.*;
public class RandomPOJOs {
static class MyPojo{
int priority;
public MyPojo(int p){ priority = p; }
@Override
public String toString(){ return "MP[" + priority + "]"; }
}
// exact numbers of pojos, random shuffling
static List<MyPojo> createPojosExact(int total, double... probabilities){
List<MyPojo> res = new ArrayList<MyPojo>(total);
int[] exactNumbers = new int[probabilities.length];
int sum = 0;
for (int i = 0; i < probabilities.length - 1; i++){
exactNumbers[i] = (int)(total * probabilities[i]);
sum += exactNumbers[i];
}
exactNumbers[exactNumbers.length - 1] = total - sum;
for (int prio = 0; prio < exactNumbers.length; prio ++)
for (int i = 0; i < exactNumbers[prio]; i++)
res.add(new MyPojo(prio));
java.util.Collections.shuffle(res);
return res;
}
// random number of pojos, random shuffling
static List<MyPojo> createPojosRandom(int total, double... probabilities){
List<MyPojo> res = new ArrayList<MyPojo>(total);
// ecdf = "empirical cumulated distribution function"
double[] ecdf = new double[probabilities.length];
for (int i = 0; i < probabilities.length; i++)
ecdf[i] = (i == 0 ? 0d : ecdf[i - 1]) + probabilities[i];
// sampling from ecdf with binary search
for (int i = 0; i < total; i++){
int binSearchRes = Arrays.binarySearch(ecdf, Math.random());
int prio = (binSearchRes >= 0) ? binSearchRes : (-binSearchRes - 1);
res.add(new MyPojo(prio));
}
return res;
}
public static void main(String... _){
System.out.println("exakt");
// exakte anzahlen von pojos mit verteilung: 0.1 mit prio 0, 0.2 mit 1, 0.4 mit 2, 0.3 mit 3
for (MyPojo pojo : createPojosExact(10, 0.1, 0.2, 0.4, 0.3)) System.out.println(pojo);
System.out.println("\nzufällig");
// zufällige anzahlen von pojos mit verteilung: 0.1 mit prio 0, 0.2 mit 1, 0.4 mit 2, 0.3 mit 3
for (MyPojo pojo : createPojosRandom(10, 0.1, 0.2, 0.4, 0.3)) System.out.println(pojo);
System.out.println("\nhistogramm: ");
// nachzählen was die random variante eigentlich ausgibt
int[] hist = new int[4];
for (MyPojo pojo : createPojosRandom(1000000, 0.1, 0.2, 0.4, 0.3)) hist[pojo.priority]++;
for (int h: hist) System.out.println(h/1000000d);
}
}