public class Test {
public static void main(String[] args) {
Pair[] options = new Pair[] {
Pair.builder().item("1元").weight(7).build(),
Pair.builder().item("2元").weight(2).build(),
Pair.builder().item("10元").weight(1).build()
};
WeightRandom rnd = new WeightRandom(options);
for (int i = 0; i < 10; i++) {
System.out.print(rnd.nextItem() + " ");
}
}
}
@Data
@Builder
public class Pair {
Object item;
int weight;
}
public class WeightRandom {
private Pair[] options;
private double[] cumulativeProbabilities;
private Random rnd;
public WeightRandom(Pair[] options) {
this.options = options;
this.rnd = new Random();
prepare();
}
private void prepare() {
int weight = 0;
for (Pair pair : options) {
weight += pair.getWeight();
}
cumulativeProbabilities = new double[options.length];
int sum = 0;
for (int i = 0; i < options.length; i++) {
sum += options[i].getWeight();
cumulativeProbabilities[i] = sum / (double) weight;
}
}
public Object nextItem() {
double randomValue = rnd.nextDouble();
int index = Arrays.binarySearch(cumulativeProbabilities, randomValue);
if (index < 0) {
index = -index-1;
}
return options[index].getItem();
}
}