Can I do the following in java without using external libraries? Maybe with if-else statements? thanks
import random
print(random.choices(['A', 'B', 'C'], [0.5, 0.3, 0.2]))
Sure. The tools required are:
java.util.Random
nextDouble
method.The algorithm is something like:
[0.5, 0.8, 1.0]
.nextDouble
with the final weight (here the final weight is 1.0, so not needed. Multiplying by 1.0 doesn't hurt, of course).Example:
public class WeightedList {
private final char[] choices;
private final double[] weights;
private final Random rnd = new Random();
public WeightedList(char[] choices, double[] weights) {
if (choices.length != weights.length) throw new IllegalArgumentException();
this.choices = Arrays.copyOf(choices);
this.weights = new double[weights.length];
double s = 0.0;
for (int i = 0; i < weights.length; i++) {
this.weights[i] = (s += weights[i]);
}
}
public char get() {
double v = rnd.nextDouble() * weights[weights.length - 1];
for (int i = 0; i < weights.length - 1; i++) {
if (v < weights[i]) return choices[i];
}
return weights[weights.length - 1];
}
}