Handle weighted random selections
mainThe NRandom.Collections namespace provides tools for weighted random selection via IWeightedCollection<T> and WeightedList<T>.
Core Types:
IWeightedCollection<T>: An interface for collections holding weighted elements.WeightedValue<T>: A struct representing a value and its associateddoubleweight.WeightedList<T>: A concrete implementation for managing weighted elements.
Operations:
Add(T value, double weight): Adds an element with a specific weight.GetRandom(): Retrieves a weighted random element.RemoveRandom(out T item): Performs a weighted random draw and removes the selected item from the list.
using NRandom.Collections;
// Create a weighted list
var weightedList = new WeightedList<string>();
// Add elements with specified weights
weightedList.Add("Legendary", 0.5);
weightedList.Add("Epic", 2.5);
weightedList.Add("Rare", 12);
weightedList.Add("Uncommon", 25);
weightedList.Add("Common", 60);
// Retrieve a weighted random element
var rarity = weightedList.GetRandom();
// Draw without duplicates
weightedList.RemoveRandom(out var item0);