| Crates.io | weighted-list |
| lib.rs | weighted-list |
| version | 0.5.0 |
| created_at | 2025-12-04 19:40:50.767278+00 |
| updated_at | 2026-01-23 10:58:38.297225+00 |
| description | A list class for weighted randomisation |
| homepage | |
| repository | https://github.com/Sup2point0/weighted-list/tree/main/rust |
| max_upload_size | |
| id | 1966952 |
| size | 107,668 |
A vector implementation for weighted randomisation.
This crate implements the WeightedList struct, an ordered collection of WeightedItems, which hold a value and weight. Indexing and random selection takes the weight of items into consideration, such that items with greater weights are more likely to be selected.
// blanket import
use weighted_list::*;
// specific imports
use weighted_list::{
WeightedList, wlist,
WeightedItem, wit,
};
// macro
let wl = wlist![
(2, "sup"),
(3, "nova"),
(5, "shard"),
];
// constructor
let wl = WeightedList::init(
[
(2, "sup"),
(3, "nova"),
(5, "shard"),
]
);
let descriptors = wlist![
(10, String::from("cool")),
(5, String::from("awesome")),
(2, String::from("elegant")),
(1, String::from("beautiful")),
];
// single selection
let word = descriptors.select_random_value(&mut rand::rng());
if let Some(chosen) = word {
println!("You look {chosen}");
// => You look cool
// (10/18 probability)
}
// multiple selection (bon builder syntax)
let words = descriptors.select_random_values()
.rng(&mut rand::rng())
.count(2)
.unique(true)
.call();
if let Some(first) = words[0] && let Some(second) = words[1] {
println!("Rust is {first} and {second}");
// => Rust is awesome and elegant
}
let wl = wlist![(1, "qi"), (2, "sup"), (5, "shard")];
let _ = wl[0]; // => WeightedItem { weight: 1, value: "qi" }
let _ = wl[1]; // => WeightedItem { weight: 2, value: "sup" }
let _ = wl[2]; // => WeightedItem { weight: 2, value: "sup" }
let _ = wl[3]; // => WeightedItem { weight: 5, value: "shard" }
let _ = wl[4]; // => WeightedItem { weight: 5, value: "shard" }
let _ = wl[5]; // => WeightedItem { weight: 5, value: "shard" }
let _ = wl[6]; // => WeightedItem { weight: 5, value: "shard" }
let _ = wl[7]; // => WeightedItem { weight: 5, value: "shard" }
let _ = wl[8]; // => panic - out of bounds!
FrozenWeightedList variant