Expand description
A list implementation for weighted randomisation.
This crate provides the WeightedList<V,W> struct, which stores values each with assigned weights. When randomly selecting items, those with a higher weight are more likely to be chosen.
§Example
use weighted_list::*;
let wl = WeightedList::<String, u8>::from([
(2, "sup".to_string()),
(3, "nova".to_string()),
(5, "shard".to_string()),
]);
for item in &wl {
println!("{} has weight {}", item.value, item.weight);
}
if let Some(result) = wl.select_random_value(&mut rand::rng()) {
println!("{result}");
}§Why might you need this?
- Weighted randomisation for a reward system
- Item stacking for an inventory system
- Statistical sampling
For more detailed guidance on how to use the struct, see WeightedList.
Macros§
- wit
- Construct a
WeightedItemfrom a(weight, value)pair. - wlist
- Construct a
WeightedListfrom the provided(weight, value)pairs.
Structs§
- Weighted
Item - An item in a
WeightedList, with avalueof typeVand aweightof numerical typeW. - Weighted
List - A homogeneous list of weighted items with values of type
Vand weights of numerical typeW.
Traits§
- Weight
- Any general numerical type, such as
u32,usize,f64. The typeWof item weights in aWeightedList<V,W>implement this trait.
Type Aliases§
- WItem
- A shorthand for
WeightedItem. - WList
- A shorthand for
WeightedList.