In reference to the top answer given in this post, I've noticed that it fails for a boundary case when rnd=sum_of_weight
. The fix is to generate random numbers in [0,sum_of_weight)
, however i was wondering why the code fails for this boundary case? Is it a flaw in the algorithm?
EDIT: Also, does the weight array need to be sorted high to low? It seems so, based on the subtraction loop.
Below is the Java code that implements the pseudo-code in the above post.
int sum_of_weight = 0;
int []choice_weight = {50, 15, 15, 10, 10}; // percentages
int num_choices = choice_weight.length;
public void init() {
for (int i = 0; i < num_choices; i++) {
sum_of_weight += choice_weight[i];
}
}
int next() {
int rnd = (int)Util.between(0, sum_of_weight);// random(sum_of_weight);
rnd=sum_of_weight; // force the exception by hitting boundary case
//System.out.print("rnd=" + rnd);
for (int i = 0; i < num_choices; i++) {
if (rnd < choice_weight[i])
return i;
rnd -= choice_weight[i];
}
throw new RuntimeException("should never get here for rnd=" + rnd);
}
public static void main(String[] args) {
SimpleWeight sw = new SimpleWeight();
sw.init();
for (int i=0; i < 10;i++) {
System.out.println(sw.next());
}
}