#[non_exhaustive]
pub struct Random { pub mt: [u32; 624], pub mti: usize, }
Expand description

The Random struct is used to generate random numbers using the Mersenne Twister algorithm.

This struct maintains an internal state for random number generation and provides methods to generate various types of random numbers.

Initialization

The random number generator can be initialized with the new method, which seeds the generator with a default value.

use vrd::Random;
let mut rng = Random::new();

Random Number Generation

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§mt: [u32; 624]

The array of unsigned 32-bit integers used to generate random numbers

§mti: usize

The current index of the array used in the generation of random numbers

Implementations§

source§

impl Random

source

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

Returns a random bool with a specified probability.

The bool method returns a random boolean value. The probability of returning true is determined by the probability parameter. This method is useful for generating random boolean outcomes, like simulating a coin flip.

Arguments
  • probability - A f64 value representing the probability of the function returning true. This should be a value between 0.0 and 1.0, where 0.0 always returns false and 1.0 always returns true.
Examples
use vrd::Random;
let mut rng = Random::new();
let random_bool = rng.bool(0.5); // 50% chance to get true
Panics

Panics if probability is not between 0.0 and 1.0.

source

pub fn bytes(&mut self, len: usize) -> Vec<u8>

Generates a vector of random bytes of the specified length.

Arguments
  • len - The length of the byte vector to be generated.
Examples
use vrd::Random;
let mut rng = Random::new();
let random_bytes = rng.bytes(10); // Generates 10 random bytes
println!("Random bytes: {:?}", random_bytes);
Returns

A Vec<u8> containing len randomly generated bytes.

source

pub fn char(&mut self) -> char

Generates a random character within the range ‘a’ to ‘z’.

Examples
use vrd::Random;
let mut rng = Random::new();
let random_char = rng.char(); // Generates a random lowercase character
println!("Random char: {}", random_char);
Returns

A char representing a randomly chosen lowercase letter from ‘a’ to ‘z’.

source

pub fn choose<T, 'a>(&'a mut self, values: &'a [T]) -> Option<&'a T>

Selects a random element from a provided slice.

Arguments
  • values - A slice of values from which to select a random element.
Examples
use vrd::Random;
let mut rng = Random::new();
let items = [1, 2, 3, 4, 5];
let random_item = rng.choose(&items);
println!("Random item from the array: {:?}", random_item);
Returns

An Option<&T> which is Some(&T) if the slice is not empty, containing a randomly chosen element from the slice. Returns None if the slice is empty.

Panics

Does not panic under normal operation.

source

pub fn float(&mut self) -> f32

Generates a random floating-point number in the range [0.0, 1.0).

Examples
use vrd::Random;
let mut rng = Random::new();
let random_float = rng.float(); // Generates a random float
println!("Random float: {}", random_float);
Returns

A f32 representing a randomly generated floating-point number.

Notes

The generated float is inclusive of 0.0 and exclusive of 1.0.

source

pub fn int(&mut self, min: i32, max: i32) -> i32

Generates a random integer within a specified range.

Arguments
  • min - The lower bound of the range (inclusive).
  • max - The upper bound of the range (inclusive).
Examples
use vrd::Random;
let mut rng = Random::new();
let random_int = rng.int(1, 10); // Generates a random integer between 1 and 10
println!("Random integer between 1 and 10: {}", random_int);
Returns

An i32 representing a randomly generated integer within the specified range.

Panics

Panics if min is greater than max.

source

pub fn uint(&mut self, min: u32, max: u32) -> u32

Generates a random unsigned integer within a specified range.

Arguments
  • min - The lower bound of the range (inclusive).
  • max - The upper bound of the range (inclusive).
Examples
use vrd::Random;
let mut rng = Random::new();
let random_uint = rng.uint(1, 100); // Generates a random unsigned integer between 1 and 100
println!("Random unsigned integer between 1 and 100: {}", random_uint);
Returns

A u32 representing a randomly generated unsigned integer within the specified range.

Panics

Panics if min is greater than max.

source

pub fn double(&mut self) -> f64

Generates a random double-precision floating-point number.

Examples
use vrd::Random;
let mut rng = Random::new();
let random_double = rng.double(); // Generates a random double
println!("Random double: {}", random_double);
Returns

A f64 representing a randomly generated double-precision floating-point number.

Notes

The generated double is a number in the range [0.0, 1.0).

source

pub fn mti(&self) -> usize

Returns the current index of the internal state array used in random number generation.

This method is useful for inspecting the state of the random number generator.

Examples
use vrd::Random;
let rng = Random::new();
let current_index = rng.mti();
println!("Current index of the RNG state array: {}", current_index);
Returns

The current index (usize) of the internal state array (mt) used by the Mersenne Twister algorithm.

source

pub fn set_mti(&mut self, value: usize)

Sets the value of the current index of the internal state array used in random number generation.

Arguments
  • value - The new index value to set for the internal state array.
Examples
use vrd::Random;
let mut rng = Random::new();
rng.set_mti(100); // Sets the current index to 100
assert_eq!(rng.mti(), 100);
Notes
  • This method allows for manual manipulation of the internal state of the random number generator.
  • It should be used with caution, as incorrect values can affect the quality of the generated random numbers.
source

pub fn new() -> Random

Creates a new instance of the Random struct, initializing the internal state for random number generation.

This method seeds the random number generator with a default value obtained from the thread’s random number generator.

The new method initializes the Random struct. It sets the initial state of the mt array using a default seed obtained from the system’s RNG. This seeding process is crucial for ensuring that each instance of Random produces a unique and unpredictable sequence of numbers.

Examples
use vrd::Random;
let mut rng = Random::new(); // Creates a new instance of Random
let random_number = rng.rand(); // Generates a random number
println!("Random number: {}", random_number);
Returns

A new instance of Random with its internal state initialized for random number generation.

Notes
  • The internal state is initialized with a seed value, ensuring that each instance of Random produces a unique sequence of random numbers.
  • The new method ensures that the internal state is appropriately set up for the Mersenne Twister algorithm.
source

pub fn pseudo(&mut self) -> u32

Generates a pseudo-random number by combining multiple random number generations.

This method enhances the randomness by XOR-ing multiple calls to the basic random number generator.

Examples
use vrd::Random;
let mut rng = Random::new();
let pseudo_random_number = rng.pseudo(); // Generates a pseudo-random number
println!("Pseudo-random number: {}", pseudo_random_number);
Returns

A u32 representing a pseudo-random number generated by combining multiple random number generations.

Notes
  • This method is intended to provide a more complex random number by aggregating multiple random number generations.
  • It might be useful in scenarios where a single call to the basic random number generator does not provide sufficient randomness.
source

pub fn rand(&mut self) -> u32

Generates a random 32-bit unsigned integer using the Mersenne Twister algorithm.

This method is the core function of the Random struct, providing the basic mechanism for generating random numbers.

The rand method generates a random 32-bit number using the current state of the mt array. It applies a series of bitwise transformations for tempering, which refines the output and improves the statistical properties of the generated numbers.

Examples
use vrd::Random;
let mut rng = Random::new();
let random_number = rng.rand(); // Generates a random 32-bit unsigned integer
println!("Random number: {}", random_number);
Returns

A u32 representing a randomly generated 32-bit unsigned integer.

Notes
  • This method updates the internal state of the random number generator each time it is called.
  • If the internal index (mti) reaches the threshold, it automatically reinitializes the internal state array.
source

pub fn random_range(&mut self, min: u32, max: u32) -> u32

Generates a random 32-bit unsigned integer within a specified range.

Arguments
  • min - The lower bound of the range (inclusive).
  • max - The upper bound of the range (exclusive).
Examples
use vrd::Random;
let mut rng = Random::new();
let random_number = rng.random_range(10, 20); // Generates a random number between 10 (inclusive) and 20 (exclusive)
println!("Random number between 10 and 20: {}", random_number);
Returns

A u32 representing a randomly generated number within the specified range.

Panics

Panics if min is not less than max.

Notes
  • This method offers a convenient way to specify the range for random number generation.
source

pub fn range(&mut self, min: i32, max: i32) -> i32

Generates a random number within a specified range of integer values.

Arguments
  • min - The lower bound of the range (inclusive).
  • max - The upper bound of the range (inclusive).
Examples
use vrd::Random;
let mut rng = Random::new();
let random_number = rng.range(1, 100); // Generates a random number between 1 and 100
println!("Random number between 1 and 100: {}", random_number);
Returns

An i32 representing a randomly generated number within the specified range.

Panics

Panics if min is greater than max.

Notes
  • This method is similar to int but allows for a different interface for specifying the range.
source

pub fn seed(&mut self, seed: u32)

Seeds the random number generator with a specified value.

This method initializes the internal state array of the generator with a given seed, affecting the sequence of random numbers generated.

The constant 1812433253u32 is used in the seeding process. It’s derived from the fractional part of the square root of 2. This particular value is chosen to provide good statistical properties for the initial array of numbers.

Arguments
  • seed - A u32 value used to seed the generator.
Examples
use vrd::Random;
let mut rng = Random::new();
rng.seed(12345); // Seeds the random number generator
let random_number = rng.rand(); // Generates a random number based on the new seed
println!("Random number with seed 12345: {}", random_number);
Notes
  • Seeding the generator is essential for reproducibility of the random number sequence.
  • Different seeds will produce different sequences, while the same seed will always produce the same sequence.
source

pub fn twist(&mut self)

Performs the “twisting” operation to update the internal state array of the random number generator.

This method is a key part of the Mersenne Twister algorithm, and it’s called internally when the generator’s index exceeds its predefined threshold.

The twist method is a key part of the Mersenne Twister algorithm. It generates a new array of 624 numbers based on the current array. This method uses bitwise operations and modular arithmetic to transform the existing numbers into a new set, thereby ‘twisting’ the current state. This is essential for maintaining the algorithm’s long period and high-quality randomness.

Examples
use vrd::Random;
let mut rng = Random::new();
rng.twist(); // Manually performs a twist operation
Notes
  • This method modifies the internal state array, ensuring that future random numbers generated are different from the previous ones.
  • It is typically not called directly by users of the Random struct, as it is automatically managed by the rand and other methods.

Trait Implementations§

source§

impl Clone for Random

source§

fn clone(&self) -> Random

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Random

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Default for Random

source§

fn default() -> Random

Returns a default random number generator

source§

impl Display for Random

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Returns a formatted string representation of the Random struct.

source§

impl Hash for Random

source§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl Ord for Random

source§

fn cmp(&self, other: &Random) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl PartialEq for Random

source§

fn eq(&self, other: &Random) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd for Random

source§

fn partial_cmp(&self, other: &Random) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Eq for Random

source§

impl StructuralEq for Random

source§

impl StructuralPartialEq for Random

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

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

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V