Struct cogs_gamedev::chance::WeightedPicker [−][src]
pub struct WeightedPicker<T> { /* fields omitted */ }
Expand description
It’s often helpful to have weighted probabilities. This struct serves as a sort of weighted bag; you can give it entries with various weights, and then randomly sample them.
This is the way Minecraft loot tables work, if this sounds familiar.
The algorithm used is Vose’s Alias Method (scroll to the bottom), which to be honest I absolutely do not understand. But it has O(n) creation and O(1) selection, so sounds good to me.
You can’t edit the probabilities after you’ve created it due to the algorithm.
Implementations
Initialize a WeightedPicker from the given items and weights.
Panics if you pass it an empty Vec.
let picker = WeightedPicker::new(vec![ ("common", 10.0), ("uncommon", 5.0), ("rare", 2.0), ("legendary", 1.0), ("mythic", 0.1), ]); let mut rng = rand::thread_rng(); for _ in 0..10 { println!("- {}", picker.get(&mut rng)); } /* A sample output: - legendary - rare - uncommon - common - common - rare - uncommon - common - common - uncommon */
Get an index into the internal list.
This is like WeightedPicker::get
, but returns the index of the
selected value instead of the value.
You can use this function to save some space by passing a vec
where T
is ()
, if you want usize
outputs, I guess.
Manually index into the picker’s array.
Manually index into the picker’s array. You can use this to mutate entries once they’ve been created.
Note there is no way to mutate probabilities after creation, nor any way to add or remove possible values.
Trait Implementations
Auto Trait Implementations
impl<T> RefUnwindSafe for WeightedPicker<T> where
T: RefUnwindSafe,
impl<T> Send for WeightedPicker<T> where
T: Send,
impl<T> Sync for WeightedPicker<T> where
T: Sync,
impl<T> Unpin for WeightedPicker<T> where
T: Unpin,
impl<T> UnwindSafe for WeightedPicker<T> where
T: UnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more
pub fn vzip(self) -> V