Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get a Weighted Random Number
public class Unit
{
public string Item { get; set; }
public int Weight { get; set; }
}
public class Program
{
public static Unit GetWeightedRandomNumber(List<Unit> list)
{
var sorted = list.OrderByDescending(x => x.Weight);
int totalWeight = sorted.Sum(x => x.Weight);
int rnd = RNGCryptoRandom.RNGCryptoRandom.GetRandomNumber(totalWeight);
Unit selected = null;
foreach (Unit unit in sorted)
{
if (rnd < unit.Weight)
{
selected = unit;
break;
}
rnd = rnd - unit.Weight;
}
return selected;
}
}
@sachintha81

This comment has been minimized.

Copy link
Owner Author

sachintha81 commented Oct 13, 2017

The GetRandomNumber() method is found here:
https://gist.github.com/sachintha81/a4613d09de6b5f9d6a1a99dbf46e2385

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.