I have a script that I'm using to select a random item from an array with a weighted chance and, for the most part, it works well. The problem comes when the index gets to the last item in the array.
Here's my code:
string[] grades = { "D", "C", "B", "A", "S" };
int[] weights = { 80, 140, 170, 180, 181 };
// 80, 60, 30, 10, 1
int iterations = 100;
void Update() {
if (iterations > 0) {
string genGrade = grades[WeightedChance(weights)];
print("Chance: " + chance + ", Grade: " + genGrade);
iterations--;
}
}
int WeightedChance(int[] weights) {
float weightSum = weights[weights.Length - 1];
float chance = Random.Range(0f, weightSum);
for (int i = 0; i < weights.Length - 1; i++) {
if (chance <= weights[i]) {
return i;
}
}
return -1;
}
From what I understand when i gets to the last item in the array it seems to skip over it and then run return -1, giving me "IndexOutOfRangeException". What I can't seem to understand is why exactly that's happening. chance generates a number between 0f and weightSum (or 181 in this case), both being inclusive as they're floats. Afterwards I check for each element in weights and see if the number generated by chance is less than or equal to each one. If all of that runs like I'm thinking it should, it should always be able to choose one of the weights, but something goes wrong when i reaches 4 (atleast that's what I'm guessing). I am new to all of this, so I apologize if I'm missing anything important or my code isn't correctly formatted.