1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use crate::fitness::FitnessValue;
use crate::genotype::Genotype;
use std::cmp::Ordering;
use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::hash::{Hash, Hasher};
pub type GenesKey = u64;
#[derive(Clone, Debug)]
pub struct Chromosome<T: Genotype> {
pub genes: Vec<T::Allele>,
pub fitness_score: Option<FitnessValue>,
}
impl<T: Genotype> Chromosome<T>
where
<T as Genotype>::Allele: Hash,
{
pub fn genes_key(&self) -> GenesKey {
let mut s = DefaultHasher::new();
self.genes.hash(&mut s);
s.finish()
}
}
impl<T: Genotype> Chromosome<T> {
pub fn new(genes: Vec<T::Allele>) -> Self {
Self {
genes,
fitness_score: None,
}
}
pub fn taint_fitness_score(&mut self) {
self.fitness_score = None;
}
}
impl<T: Genotype> PartialEq for Chromosome<T> {
fn eq(&self, other: &Self) -> bool {
self.fitness_score == other.fitness_score
}
}
impl<T: Genotype> Eq for Chromosome<T> {}
impl<T: Genotype> PartialOrd for Chromosome<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.fitness_score.cmp(&other.fitness_score))
}
}
impl<T: Genotype> Ord for Chromosome<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap_or(Ordering::Equal)
}
}
impl<T: Genotype> fmt::Display for Chromosome<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(score) = self.fitness_score {
write!(f, "fitness score {}", score)
} else {
write!(f, "no fitness score")
}
}
}