Search Unity

Question Probability Calculation!

Discussion in 'Scripting' started by hikariakio, Aug 6, 2020.

  1. hikariakio

    hikariakio

    Joined:
    Dec 19, 2016
    Posts:
    25
    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?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    That's basically a weighted random selector. Here's a simple function that should accomplish this.

    Code (csharp):
    1. float[] probabilities = new float[]{15f,15f,15f,13f,12f,10f,10f,5f,3f,3f,2f};
    2. int GetRandomWeighted() {
    3.  
    4. //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
    5. float totalProbability = 0f;
    6. foreach (float f in probabilities) totalProbability += f;
    7.  
    8. // choose our random value
    9. float randomValue = Random.value * totalProbability;
    10.  
    11. // crawl along our array until we reach our value
    12. float crawlingValue = 0f;
    13. for (int i=0; i<probabilities.Length; i++) {
    14. crawlingValue += probabilities[i];
    15. if (crawlingValue >= randomValue) return i;
    16. }
    17. return -1; //this should never be reached unless I wrote this wrong
    18. }
     
    hikariakio and PraetorBlue like this.