I am using this to try to create a weighted random:
int choice_weight[] = { 25, 25, 25, 25 };
int num_choices = choice_weight.length;
Random random = new Random();
int i;
int sum_of_weight = 0;
for (i = 0; i < num_choices; i++) {
sum_of_weight += choice_weight[i];
}
int rnd = random.nextInt(sum_of_weight);
System.out.println(rnd);
for (i = 0; i < num_choices; i++) {
if (rnd < choice_weight[i])
rnd -= choice_weight[i];
}
I am using a swtich statement to test and see if the cases are:
case 1:
case 2:
case 3:
case 4:
The problem is that random.nextInt(sum_of_weight) is generating numbers between 100 and 0 which is based on my 4 weights of 25,25,25,25. I need a number to match one of the possible cases 1-4? Or should I change up my method of testing?
This whole process is kind of confusing me, some help would be greatly appreciated.
So basically it will be a 25 percent chance a particular number will be chosen. Also, I will be changing the percentages throughout the program’s life cycle.
Shouldn’t you “increase” your range when testing for your number? Ie:
Basically you’re generating a number between 0-99 and checking if you values are:
On second look the way you have it will work too (w/ adjustments):