From a880c1b3954633e249d70ce5531f4f47093da939 Mon Sep 17 00:00:00 2001 From: Rutherther Date: Mon, 27 Oct 2025 20:45:53 +0100 Subject: [PATCH] feat: add best replacement --- codes/eoa_lib/src/replacement.rs | 58 ++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/codes/eoa_lib/src/replacement.rs b/codes/eoa_lib/src/replacement.rs index 3c79db67e44370ae69ce61d95a67e61a0e671bcb..c6dfb20fe6e3cae488e217de8537e65db8864b6f 100644 --- a/codes/eoa_lib/src/replacement.rs +++ b/codes/eoa_lib/src/replacement.rs @@ -1,19 +1,34 @@ use rand::{seq::IteratorRandom, RngCore}; +use std::fmt::Debug; use crate::{comparison::BetterThanOperator, fitness::FitnessFunction, selection::{Selection, TournamentSelection}}; -#[derive(Clone)] +fn extract_by_indices(mut x: Vec, mut idxs: Vec) -> Vec { + idxs.sort_unstable_by(|a, b| b.cmp(a)); + + let mut result = Vec::with_capacity(idxs.len()); + for idx in idxs { + if idx < x.len() { + result.push(x.swap_remove(idx)); + } + } + + result.reverse(); + result +} + +#[derive(Clone, Debug)] pub struct Population { population: Vec } -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct EvaluatedChromosome { pub chromosome: TChromosome, pub evaluation: TResult, } -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct EvaluatedPopulation { pub population: Vec> } @@ -25,6 +40,10 @@ impl Population { } } + pub fn from_iterator(iter: impl Iterator) -> Self { + Self::from_vec(iter.collect()) + } + pub fn evaluate>(self, func: &T) -> Result, T::Err> { EvaluatedPopulation::evaluate( self.population, @@ -122,6 +141,39 @@ pub trait Replacement { ) -> EvaluatedPopulation; } +pub struct BestReplacement; +impl BestReplacement { + pub fn new() -> Self { + Self + } +} + +impl Replacement for BestReplacement { + fn replace( + &mut self, + parents_evaluations: EvaluatedPopulation, + offsprings_evaluations: EvaluatedPopulation, + better_than: &dyn BetterThanOperator + ) -> EvaluatedPopulation { + let count = parents_evaluations.population.len(); + let mut population = parents_evaluations; + population.join(offsprings_evaluations); + + let mut idxs = (0..population.population.len()) + .collect::>(); + idxs.sort_unstable_by(|&i, &j| better_than.ordering( + &population.population[i].evaluation, + &population.population[j].evaluation) + ); + + idxs.truncate(count); + + EvaluatedPopulation::from_vec( + extract_by_indices(population.deconstruct(), idxs) + ) + } +} + pub struct GenerationalReplacement; impl Replacement for GenerationalReplacement { fn replace(