Created
October 13, 2017 18:29
-
-
Save sachintha81/0a3283406bc4f2bd0455e63fd0490512 to your computer and use it in GitHub Desktop.
Get a Weighted Random Number
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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
GetRandomNumber()
method is found here:https://gist.github.com/sachintha81/a4613d09de6b5f9d6a1a99dbf46e2385