Skip to content

Instantly share code, notes, and snippets.

@saint-angels
Created December 27, 2019 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saint-angels/938539cb098d868b28b29bbbb4d1f390 to your computer and use it in GitHub Desktop.
Save saint-angels/938539cb098d868b28b29bbbb4d1f390 to your computer and use it in GitHub Desktop.
Weighted Random
private int RandomWeighted(List<int> weights)
{
int accumulatedWeigts = 0;
for (int i = 0; i < weights.Count; i++)
{
accumulatedWeigts += weights[i];
weights[i] = accumulatedWeigts;
}
//If accumulated weights is 0, choose random index. Otherwise, logic would always select 1st element
if (accumulatedWeigts == 0)
{
return UnityEngine.Random.Range(0, accumulatedWeigts + 1);
}
var rollResult = Randomizer.Roll(Randomizer.EventType.DecisionMaker, 0, accumulatedWeigts + 1);
for (int i = 0; i < weights.Count; i++)
{
if (rollResult <= weights[i])
{
return i;
}
}
Debug.LogError($"No weights provided for weighted random!");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment