pumpkin_solver

Trait Random

source
pub trait Random: Debug {
    // Required methods
    fn generate_bool(&mut self, probability: f64) -> bool;
    fn generate_usize_in_range(&mut self, range: Range<usize>) -> usize;
}
Expand description

A trait for generating random values; an example of where this is used is in the InDomainRandom value selector where it is used to determine which value in the domain to select.

At the moment, the randomness in the solver is controlled by the Solver and the random number generator is by this structure to the SelectionContext.

§Testing

We have also created an implementation of this trait which takes as input a list of usizes and bools and returns them in that order. This allows the user to define deterministic test-cases while the implementation makes use of an implementation of the Random trait.

Required Methods§

source

fn generate_bool(&mut self, probability: f64) -> bool

Generates a bool with probability probability of being true. It should hold that probability ∈ [0, 1], this method will panic if this is not the case.

§Example

This example will show how to use a concrete implementation of SeedableRng to implement a fair coin toss (e.g. a bernoulli trial with probability 0.5).

// First we create our random object
let mut rng = SmallRng::seed_from_u64(42);
// Then we flip a coin with probability 0.5
let coin_flip_outcome = rng.generate_bool(0.5);
// A sanity check to ensure that the method has not panicked
assert!(coin_flip_outcome || !coin_flip_outcome);

// If we provide a probability outside of the expected range then the method is expected to panic!
let result = std::panic::catch_unwind(|| rng.clone().generate_bool(120.0));
assert!(result.is_err());
source

fn generate_usize_in_range(&mut self, range: Range<usize>) -> usize

Generates a random usize in the provided range with equal probability; this can be seen as sampling from a uniform distribution in the range [range.start, range.end)

§Example

This example will show how to use a concrete implementation of SeedableRng to implement selecting a random element from a list.

// First we create our random object
let mut rng = SmallRng::seed_from_u64(42);
// Then we create the elements to select from
let elements = vec!["This", "is", "a", "test"];
// Finally we generate a random number in the range [0, |elements|)
let selected_index = rng.generate_usize_in_range(0..elements.len());
assert!(selected_index >= 0 && selected_index < elements.len());

Implementors§

source§

impl<T> Random for T
where T: SeedableRng + Rng + Debug,