Suppose I have an array of
array = { 20,18,17,13,12,10,10,5,3,2}
which means probability of getting “0” is 15% , getting “9” is 2% etc.
I am thinking of several ways but what algorithm will be the best for achieving my goal?
Suppose I have an array of
array = { 20,18,17,13,12,10,10,5,3,2}
which means probability of getting “0” is 15% , getting “9” is 2% etc.
I am thinking of several ways but what algorithm will be the best for achieving my goal?
That’s basically a weighted random selector. Here’s a simple function that should accomplish this.
float[] probabilities = new float[]{15f,15f,15f,13f,12f,10f,10f,5f,3f,3f,2f};
int GetRandomWeighted() {
//first, calculate the totals from the array; this will prevent the algorithm from breaking if you change the amount of numbers and/or if they don't add up to exactly 100
float totalProbability = 0f;
foreach (float f in probabilities) totalProbability += f;
// choose our random value
float randomValue = Random.value * totalProbability;
// crawl along our array until we reach our value
float crawlingValue = 0f;
for (int i=0; i<probabilities.Length; i++) {
crawlingValue += probabilities[i];
if (crawlingValue >= randomValue) return i;
}
return -1; //this should never be reached unless I wrote this wrong
}