Skip to content

Instantly share code, notes, and snippets.

@sachintha81
Created October 13, 2017 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachintha81/0a3283406bc4f2bd0455e63fd0490512 to your computer and use it in GitHub Desktop.
Save sachintha81/0a3283406bc4f2bd0455e63fd0490512 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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