ProbabilityUtils.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. namespace HQFPSWeapons
  4. {
  5. /// <summary>
  6. ///
  7. /// </summary>
  8. public class ProbabilityUtils : MonoBehaviour
  9. {
  10. /// <summary>
  11. /// Return an index randomly chosen following the distribution specified by a list of probabilities
  12. /// </summary>
  13. /// <returns>
  14. /// An index in range [0, probabilities.Length) following the distribution specified in probabilites.
  15. /// </returns>
  16. /// <param name="probabilities">
  17. /// A list of probabilities from which to choose an index. All values must be >= 0!
  18. /// </param>
  19. public static int RandomChoiceFollowingDistribution(List<float> probabilities)
  20. {
  21. // Sum to create CDF:
  22. float[] cdf = new float[probabilities.Count];
  23. float sum = 0;
  24. for (int i = 0; i < probabilities.Count; ++i)
  25. {
  26. cdf[i] = sum + probabilities[i];
  27. sum = cdf[i];
  28. }
  29. // Choose from CDF:
  30. float cdf_value = Random.Range(0f, cdf[probabilities.Count - 1]);
  31. int index = System.Array.BinarySearch(cdf, cdf_value);
  32. if (index < 0)
  33. // If not found (probably won't be) BinarySearch returns bitwise complement of next-highest index.
  34. index = ~index;
  35. return index;
  36. }
  37. }
  38. }