use core::num::NonZeroUsize;
use rand::Rng;
use crate::gene::Gene;
use super::Mutation;
#[derive(Copy, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct Remove {
pub chance: f64,
pub min_genes: NonZeroUsize,
}
impl<G, RNG> Mutation<Vec<G>, RNG> for Remove
where
G: Gene,
RNG: Rng,
{
fn mutate(&self, genotype: &mut Vec<G>, rng: &mut RNG) {
assert!(
self.chance >= 0.0_f64,
"chance of mutation has to be above or equal 0.0, but is {}",
self.chance
);
assert!(
self.chance <= 1.0_f64,
"chance of mutation has to be below or equal 1.0, but is {}",
self.chance
);
if genotype.len() <= self.min_genes.get() {
return;
}
if rng.gen_bool(self.chance) {
let gene_to_remove = rng.gen_range(0..genotype.len());
let _removed = genotype.remove(gene_to_remove);
}
}
}
impl<RNG> Mutation<String, RNG> for Remove
where
RNG: Rng,
{
fn mutate(&self, genotype: &mut String, rng: &mut RNG) {
assert!(
self.chance >= 0.0_f64,
"chance of mutation has to be above or equal 0.0, but is {}",
self.chance
);
assert!(
self.chance <= 1.0_f64,
"chance of mutation has to be below or equal 1.0, but is {}",
self.chance
);
if genotype.len() <= self.min_genes.get() {
return;
}
if rng.gen_bool(self.chance) {
let mut chars = genotype.chars().collect::<Vec<_>>();
let gene_to_remove = rng.gen_range(0..chars.len());
let _ = chars.remove(gene_to_remove);
*genotype = chars.iter().collect::<String>();
}
}
}
#[cfg(test)]
mod tests {
use rand::rngs::SmallRng;
use rand::SeedableRng;
use super::{Mutation, Remove};
#[test]
fn vector() {
let mutation = Remove {
chance: 1.0_f64,
min_genes: 1.try_into().unwrap(),
};
let mut rng = SmallRng::seed_from_u64(0);
let mut array = vec![0, 1, 2, 3, 4];
mutation.mutate(&mut array, &mut rng);
assert_eq!(array, [0, 1, 3, 4]);
}
#[test]
fn vector_min_genes() {
let mutation = Remove {
chance: 1.0_f64,
min_genes: 5.try_into().unwrap(),
};
let mut rng = SmallRng::seed_from_u64(0);
let mut array = vec![0, 1, 2, 3, 4];
mutation.mutate(&mut array, &mut rng);
assert_eq!(array, [0, 1, 2, 3, 4]);
}
#[test]
fn string() {
let mutation = Remove {
chance: 1.0_f64,
min_genes: 1.try_into().unwrap(),
};
let mut rng = SmallRng::seed_from_u64(0);
let mut string = String::from("test");
mutation.mutate(&mut string, &mut rng);
assert_eq!(string, "tet");
}
}