pub struct WeightedCollection<T> {
items: Vec<(T, f64)>,
total_weight: f64,
}Expand description
A collection of items with associated weights for probabilistic selection.
Weights must be positive (> 0.0); items with non-positive weights are
treated as having zero probability for pick_one /
pick_index and are placed at the end of the shuffled
output in into_shuffled.
§Examples
use hopr_statistics::WeightedCollection;
let wc = WeightedCollection::new(vec![("rare", 0.1), ("common", 10.0)]);
let picked = wc.pick_one().expect("non-empty collection");
assert!(picked == "rare" || picked == "common");Fields§
§items: Vec<(T, f64)>§total_weight: f64Pre-computed sum of positive weights (cached to avoid recomputing on every pick).
Implementations§
Source§impl<T> WeightedCollection<T>
impl<T> WeightedCollection<T>
Sourcepub fn new(items: Vec<(T, f64)>) -> Self
pub fn new(items: Vec<(T, f64)>) -> Self
Create a new weighted collection from items paired with their weights.
Sourcepub fn pick_index(&self) -> Option<usize>
pub fn pick_index(&self) -> Option<usize>
Returns the index of a randomly selected item, weighted by probability proportional to its weight.
Returns None if the collection is empty or all weights are non-positive.
Source§impl<T> WeightedCollection<T>
impl<T> WeightedCollection<T>
Source§impl<T: Clone> WeightedCollection<T>
impl<T: Clone> WeightedCollection<T>
Source§impl<T> WeightedCollection<T>
impl<T> WeightedCollection<T>
Sourcepub fn into_shuffled(self) -> Vec<T>
pub fn into_shuffled(self) -> Vec<T>
Consume the collection and return items in a weighted random permutation.
Uses the Efraimidis–Spirakis algorithm: each item is assigned a key
random()^(1/weight) and the items are sorted by descending key.
Higher-weight items appear earlier with higher probability, but all
items retain a nonzero chance of appearing at any position.