Example about generating random number using the alias method in C#
public static class RandomExtensions
{
public static int GetAlias(this Random rnd, IEnumerable<int> probs)
{
int random = rnd.Next(probs.Sum());
int sum = 0;
int idx = 0;
foreach (var p in probs)
{
sum += p;
if (sum >= random)
break;
idx++;
}
return idx;
} // GetAlias
}
We pass the method a list of int containing the probability we want for that index.
Test program
class Program
{
class Animal
{
public Animal(string name) {
Name = name;
}
public string Name { get; set; }
public int Count { get; set; }
}
static void Main(string[] args)
{
List<Animal> values = new List<Animal>
{
new Animal("Cat"),
new Animal("Dog"),
new Animal("Sheep"),
new Animal("Cow"),
new Animal("Turtle"),
};
int[] probs = new int[] { 10, 50, 10, 10, 20 };
Random rnd = new Random();
for (int i=0; i < 100; i++) {
int number = rnd.GetAlias(probs);
values[number].Count++;
}
foreach (var a in values) {
Console.WriteLine($"{string.Format("{0,-10}", a.Name)}: {string.Format("{0,2}", a.Count)}");
}
}
}
Test program output
Cat : 6
Dog : 49
Sheep : 12
Cow : 11
Turtle : 22