Skip to main content

Crate weighted_list

Crate weighted_list 

Source
Expand description

Data structures for weighted randomisation.

This crate provides the WeightedList<V,W> struct, storing WeightedItems with a value and weight. When picking items randomly, 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§

NumCastError
An error returned when failing to cast one numeric type to another, which may be required for certain WeightedList operations.
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 numerical type, such as u32, usize, f64. The type W of item weights in a WeightedList<V,W> must implement this trait.

Type Aliases§

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