Skip to content

Instantly share code, notes, and snippets.

@develohpanda
Last active April 7, 2020 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save develohpanda/eb2288aed8c72aead22ced7665ba8789 to your computer and use it in GitHub Desktop.
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
/// <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