Last active
April 7, 2020 16:34
-
-
Save develohpanda/eb2288aed8c72aead22ced7665ba8789 to your computer and use it in GitHub Desktop.
Weighted Random Selection - a simplified implementation of the solution found at http://programmers.stackexchange.com/a/150642/244423
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
/// <summary> | |
/// Selects a random element from input list using the weights on T to sway selection. | |
/// T must have a Weight property on it. | |
/// </summary> | |
public T SelectRandom<T>(List<T> objects) | |
{ | |
int totalWeight = 0; | |
T selected = default(T); | |
foreach (T obj in objects) | |
{ | |
int weight = obg.Weight; | |
int r = new Random().Next(totalWeight + obj.Weight); | |
if (r >= totalWeight) | |
selected = obj; | |
totalWeight += weight; | |
} | |
return selected; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment