Created
December 27, 2019 07:15
-
-
Save saint-angels/938539cb098d868b28b29bbbb4d1f390 to your computer and use it in GitHub Desktop.
Weighted Random
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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