Skip to content

Instantly share code, notes, and snippets.

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;
rnd = rnd - unit.Weight;
return selected;

This comment has been minimized.

Copy link
Owner Author

@sachintha81 sachintha81 commented Oct 13, 2017

The GetRandomNumber() method is found here:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment