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 item from the list.

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.

The same as creating a WeightedPicker and then calling get, but you don’t need to actually make the WeightedPicker.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.