use crate::random::{random_normal_array, random_uniform_array, thread_rng};
use ::ndarray::{Array2, Ix2};
use rand_distr::{Normal, Uniform};
pub fn random_f64() -> f64 {
crate::random::convenience::uniform()
}
pub fn random_f32() -> f32 {
random_f64() as f32
}
pub fn random_int(min: i64, max: i64) -> i64 {
crate::random::convenience::integer(min, max)
}
pub fn random_usize(min: usize, max: usize) -> usize {
random_int(min as i64, max as i64) as usize
}
pub fn random_bool() -> bool {
crate::random::convenience::boolean()
}
pub fn random_bool_with_prob(prob: f64) -> bool {
random_f64() < prob
}
pub fn random_vector(size: usize) -> Vec<f64> {
let mut rng = thread_rng();
(0..size)
.map(|_| rng.sample(Uniform::new(0.0, 1.0).expect("Operation failed")))
.collect()
}
pub fn random_int_vector(size: usize, min: i64, max: i64) -> Vec<i64> {
(0..size).map(|_| random_int(min, max)).collect()
}
pub fn random_matrix(rows: usize, cols: usize) -> Array2<f64> {
let mut rng = thread_rng();
random_uniform_array(Ix2(rows, cols), &mut rng)
}
pub fn random_normal_matrix(rows: usize, cols: usize, mean: f64, std: f64) -> Array2<f64> {
let mut rng = thread_rng();
random_normal_array(Ix2(rows, cols), mean, std, &mut rng)
}
pub fn pick_one<T>(items: &[T]) -> Option<&T> {
if items.is_empty() {
None
} else {
let index = random_usize(0, items.len() - 1);
Some(&items[index])
}
}
pub fn pick_many<T: Clone>(items: &[T], count: usize) -> Vec<T> {
(0..count)
.filter_map(|_| pick_one(items))
.cloned()
.collect()
}
pub fn shuffle<T>(items: &mut Vec<T>) {
use crate::random::seq::SliceRandom;
let mut rng = crate::random::thread_rng();
items.shuffle(&mut rng);
}
pub fn shuffled<T: Clone>(items: &[T]) -> Vec<T> {
let mut result = items.to_vec();
shuffle(&mut result);
result
}
pub fn random_text(length: usize) -> String {
const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
(0..length)
.map(|_| {
let idx = random_usize(0, CHARS.len() - 1);
CHARS[idx] as char
})
.collect()
}
pub fn random_hex(byte_length: usize) -> String {
(0..byte_length)
.map(|_| format!("{:02x}", random_usize(0, 255)))
.collect()
}
pub fn coin_flip() -> bool {
random_bool()
}
pub fn dice_roll() -> i64 {
random_int(1, 6)
}
pub fn dice_roll_sum(count: usize) -> i64 {
(0..count).map(|_| dice_roll()).sum()
}
pub fn random_percentage() -> f64 {
random_f64() * 100.0
}
pub fn weighted_choice<T: Clone>(items: &[T], weights: &[f64]) -> Option<T> {
if items.len() != weights.len() || items.is_empty() {
return None;
}
let total: f64 = weights.iter().sum();
if total <= 0.0 {
return None;
}
let mut cumulative = 0.0;
let target = random_f64() * total;
for (item, &weight) in items.iter().zip(weights.iter()) {
cumulative += weight;
if target <= cumulative {
return Some(item.clone());
}
}
items.last().cloned()
}