pub struct WeightedBag<T, W: Weight> { /* private fields */ }Available on crate feature
bag only.Expand description
A WeightedBag is a collection that holds entries of type T with associated weights of type W.
The weights determine the likelihood of selecting each entry when retrieving a random item from the bag.
§Type Parameters
T: The type of the entries stored in the bag.W: A type that implements the Weight trait, representing the weight of each entry.
§Features
This struct can derive Serialize and Deserialize traits when the serde feature is enabled.
It can also be constructed from a vector of tuples Vec<(T, W)> containing entries and their corresponding weights.
§Example
let mut bag: random::WeightedBag<&str, u32> = random::WeightedBag::default();
bag.add_entry("apple", 2);
bag.add_entry("banana", 1);
let random_fruit: Option<&&str> = bag.try_get_random();Implementations§
Source§impl<T, W: Weight> WeightedBag<T, W>
impl<T, W: Weight> WeightedBag<T, W>
Sourcepub fn add_entry(&mut self, t: T, weight: W)
pub fn add_entry(&mut self, t: T, weight: W)
Adds an entry with given weight to the bag
Panics if the weight is 0
Sourcepub fn try_get_random(&self) -> Option<&T>
pub fn try_get_random(&self) -> Option<&T>
Retrieve a random entry from the bag, chances are based on weight
Sourcepub fn get_random(&self) -> &T
pub fn get_random(&self) -> &T
Trait Implementations§
Source§impl<T, W: Weight> Default for WeightedBag<T, W>
impl<T, W: Weight> Default for WeightedBag<T, W>
Source§impl<'de, T, W> Deserialize<'de> for WeightedBag<T, W>
impl<'de, T, W> Deserialize<'de> for WeightedBag<T, W>
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
Auto Trait Implementations§
impl<T, W> Freeze for WeightedBag<T, W>where
W: Freeze,
impl<T, W> RefUnwindSafe for WeightedBag<T, W>where
W: RefUnwindSafe,
T: RefUnwindSafe,
impl<T, W> Send for WeightedBag<T, W>
impl<T, W> Sync for WeightedBag<T, W>
impl<T, W> Unpin for WeightedBag<T, W>
impl<T, W> UnwindSafe for WeightedBag<T, W>where
W: UnwindSafe,
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more