Crate weighted_list

Crate weighted_list 

Source
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 WeightedItem from a (weight, value) pair.
wlist
Construct a WeightedList from the provided (weight, value) pairs.

Structs§

WeightedItem
An item in a WeightedList, with a value of type V and a weight of numerical type W.
WeightedList
A homogeneous list of weighted items with values of type V and weights of numerical type W.

Traits§

Weight
Any general numerical type, such as u32, usize, f64. The type W of item weights in a WeightedList<V,W> implement this trait.

Type Aliases§

WItem
A shorthand for WeightedItem.
WList
A shorthand for WeightedList.