From d4df3887a92f94774475ea5fafb33408e1ba10a7 Mon Sep 17 00:00:00 2001 From: Rutherther Date: Sun, 26 Oct 2025 21:42:21 +0100 Subject: [PATCH] feat: add pairing of parents --- env/src/main.rs | 1 + env/src/pairing.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 env/src/pairing.rs diff --git a/env/src/main.rs b/env/src/main.rs index 1a9fa9efd93412a9f642460bd2af37b8228b38de..50c14dcd56cc4247be9641df42ce074d2a2f2f0d 100644 --- a/env/src/main.rs +++ b/env/src/main.rs @@ -1,4 +1,5 @@ pub mod fitness; +pub mod pairing; pub mod crossover; pub mod bounded; pub mod selection; diff --git a/env/src/pairing.rs b/env/src/pairing.rs new file mode 100644 index 0000000000000000000000000000000000000000..4d71f157c4cb6a2054b3955a9bfb00ebf6d2f238 --- /dev/null +++ b/env/src/pairing.rs @@ -0,0 +1,67 @@ +use std::marker::PhantomData; + +use crate::replacement::EvaluatedPopulation; + +pub type ParentPairing = (usize, usize); + +pub trait Pairing { + type Chromosome; + type Out; + + fn pair>( + &mut self, + population: &EvaluatedPopulation, + parents: T + ) -> impl Iterator; +} + +pub struct AdjacentPairing { + _phantom1: PhantomData, + _phantom2: PhantomData, +} + +impl AdjacentPairing { + pub fn new() -> Self { + Self { + _phantom1: PhantomData, + _phantom2: PhantomData, + } + } +} + +impl Pairing for AdjacentPairing { + type Chromosome = TChromosome; + type Out = TOutput; + + fn pair>( + &mut self, + _: &EvaluatedPopulation, + parents: T + ) -> impl Iterator { + AdjacentIterator(parents, 0) + } +} + +pub struct AdjacentIterator>(T, usize); + +impl> Iterator for AdjacentIterator { + type Item = ParentPairing; + + fn next(&mut self) -> Option { + let first = self.0.next(); + let second = self.0.next(); + + match (first, second) { + // Still two elements left, return them + (Some(first), Some(second)) => { + self.1 = second; // Save previous + Some((first, second)) + }, + // Only one element remaining, return it and the previous one + (Some(first), _) => Some((first, self.1)), + (None, Some(_)) => panic!("Iterators cannot return something after they return none."), + // No more elements + _ => None + } + } +}