radiate_rust/engines/codexes/
subset_codex.rs

1use crate::engines::genome::{chromosome::Chromosome, genes::bit_gene::BitGene, genotype::Genotype, genes::gene::Gene};
2
3use super::Codex;
4
5pub struct SubSetCodex<'a, T> {
6    pub items: &'a Vec<T>,
7}
8
9impl<'a, T> SubSetCodex<'a, T> {
10    pub fn new(items: &'a Vec<T>) -> Self {
11        Self { items }
12    }
13}
14
15impl<'a, T> Codex<BitGene, bool, Vec<&'a T>> for SubSetCodex<'a, T> {
16    fn encode(&self) -> Genotype<BitGene, bool> {
17        Genotype {
18            chromosomes: vec![Chromosome::from_genes(
19                self.items
20                    .iter()
21                    .map(|_| BitGene::new())
22                    .collect::<Vec<BitGene>>(),
23            )],
24        }
25    }
26
27    fn decode(&self, genotype: &Genotype<BitGene, bool>) -> Vec<&'a T> {
28        let mut result = Vec::new();
29        for (i, gene) in genotype.iter().next().unwrap().iter().enumerate() {
30            if *gene.allele() {
31                result.push(&self.items[i]);
32            }
33        }
34
35        result
36    }
37}