Very fast C# class for weighted random picking.
This repository contains code for selecting items randomly based on weights. It is very commonly used thing in video game development and it is suprisingly tricky to get it right.
You have two options:
This picture demostrates what is happening under hood, to achieve good performance.
Just use DynamicRandomSelector, and do not forget to call Build method after modifying (adding & removing) it.
var selector = new DynamicRandomSelector<float>();
// adding items
for (int i = 0; i < 32; i++) {
var item = i;
var unnormalizedWeight = Mathf.Sqrt(i + 1); //non zero weight
selector.Add(item, unnormalizedWeight);
}
// building after modification is complete
selector.Build();
// picking random items
for (int i = 0; i < 10000; i++)
var randomItem = selector.SelectRandomItem();