use rand::Rng;
use crate::binary_string::BinaryString;
pub trait PerturbationOperator {
type Chromosome;
fn perturb(self: &mut Self, chromosome: &Self::Chromosome) -> Self::Chromosome;
}
pub struct BinaryStringBitPerturbation<TRng: Rng> {
rng: TRng,
p: f64,
}
impl BinaryStringBitPerturbation<rand::rngs::ThreadRng> {
pub fn new(p: f64) -> Self {
Self {
rng: rand::rng(),
p
}
}
}
impl<TRng: Rng> PerturbationOperator for BinaryStringBitPerturbation<TRng> {
type Chromosome = BinaryString;
fn perturb(self: &mut Self, chromosome: &Self::Chromosome) -> Self::Chromosome {
chromosome.perturb(&mut self.rng, self.p)
}
}
#[test]
fn test_perturb() {
let mut rng = rand::rng();
assert_eq!(
*BinaryString::new(vec![1, 1, 0, 0])
.perturb(&mut rng, 1.0)
.vec(),
vec![0, 0, 1, 1]
);
assert_eq!(
*BinaryString::new(vec![1, 1, 0, 0])
.perturb(&mut rng, 0.0)
.vec(),
vec![1, 1, 0, 0]
);
}