I'm not sure what the technical term is here so a term I can search would be appreciated.
Let's say a character has multiple decisions of different weights.
Decision A: 1
Decision B: 3
Decision C: 5
Sum: 9
What the code does is that it adds them together, such that there's a 1/9 odds of making Decision A, 3/9 of making Decision B, 5/9 of making Decision C.
There are factors that remove and add certain decisions from the pool. These weights are not fixed (e.g. B may be 2 for more intelligent characters, or split into B1 and B2 with their own respective weight).
Right now what I'm doing is just a linear search like the following (in JavaScript):
let totalWeight = 0;
for (let i = array.length - 1; i >= 0; i--) {
totalWeight += array[i].weight;
}
// this function rolls a random number from 1 to totalWeight
let r = roll(1, totalWeight);
let search = 1;
for (let i = 0; i < array.length; i++) {
let w = array[i].weight;
if (r >= search && r < (search+w)){
return array[i];
}
search += w;
}
But this doesn't seem very efficient. It looks like there can be a binary search algorithm here but I can't seem to think of one. Any ideas?