Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Other Example of class to select random option with percentages

Discussion in 'Scripting' started by Scorpin, Mar 5, 2023.

  1. Scorpin

    Scorpin

    Joined:
    Jun 27, 2018
    Posts:
    4
    Hi, I end using this class I modified for generic types and Unity from https://stackoverflow.com/a/48267598, in case you need something like this :)

    Code (CSharp):
    1. public class ProportionalRandomSelector<T> {
    2.  
    3.         private readonly Dictionary<T, int> percentageItemsDict;
    4.  
    5.         public ProportionalRandomSelector() => percentageItemsDict = new();
    6.  
    7.         public void AddPercentageItem(T item, int percentage) => percentageItemsDict.Add(item, percentage);
    8.  
    9.         public T SelectItem() {
    10.          
    11.             // Calculate the summa of all portions.
    12.             int poolSize = 0;
    13.             foreach (int i in percentageItemsDict.Values) {
    14.                 poolSize += i;
    15.             }
    16.  
    17.             // Get a random integer from 1 to PoolSize.
    18.             int randomNumber = Random.Range(1, poolSize);
    19.  
    20.             // Detect the item, which corresponds to current random number.
    21.             int accumulatedProbability = 0;
    22.             foreach (KeyValuePair<T, int> pair in percentageItemsDict) {
    23.                 accumulatedProbability += pair.Value;
    24.                 if (randomNumber <= accumulatedProbability)
    25.                     return pair.Key;
    26.             }
    27.          
    28.             return default;  // this code will never come while you use this programm right :)
    29.      
    30.         }
    31.  
    32.     }
    33.  
    34. //Example of use. You can use any type for the item too, and don't need an internal struct for the use.
    35. public class Behaviour : MonoBehaviour {
    36.  
    37.    ProportionalRandomSelector<string> randomSelector = new();
    38.    randomSelector.AddPercentageItem("Option1", 20);
    39.    randomSelector.AddPercentageItem("Option2", 30);
    40.    randomSelector.AddPercentageItem("Option3", 30);
    41.    randomSelector.AddPercentageItem("Option4", 15);
    42.    randomSelector.AddPercentageItem("Option5", 5);
    43.    string result = randomSelector.SelectItem();
    44.  
    45. }
     
    Last edited: Mar 5, 2023
    Olipool likes this.