-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiophantus_equation.rs
57 lines (49 loc) · 1.58 KB
/
diophantus_equation.rs
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
use core::{
iter::Sum,
ops::{Mul, Sub},
};
use chromosome::Fitness;
use chromosome::{Chromosome, DefaultSimulator, FitnessSelector, Simulator};
use rand_pcg::Pcg64;
use rand_seeder::Seeder;
struct DiophantusEquation<'a, 'b, T> {
coefficients: &'a Vec<T>,
result: &'b T,
}
impl<'a, 'b, T> DiophantusEquation<'a, 'b, T> {
fn new(coefficients: &'a Vec<T>, result: &'b T) -> Self {
DiophantusEquation {
coefficients: coefficients,
result: result,
}
}
}
impl<'a, 'b, T: Mul<Output = T> + Sum + Sub<Output = T> + Into<f64> + Clone> Fitness
for DiophantusEquation<'a, 'b, T>
{
type Value = T;
fn fitness(self: &Self, chromosome: &Chromosome<T>) -> T {
(0..usize::min(self.coefficients.len(), chromosome.genes.len()))
.map(|i| self.coefficients[i].clone() * chromosome.genes[i].clone())
.sum::<T>()
- self.result.clone()
}
fn is_ideal_fitness(&self, fitness: Self::Value) -> bool {
fitness.into() == 0_f64
}
}
#[test]
fn diophantus_equation() {
let mut rng: Pcg64 = Seeder::from([23, 87, 85]).make_rng();
let coefs = vec![2_i32, 23, 54, 1];
let equation = DiophantusEquation::new(&coefs, &2);
let sim_result = DefaultSimulator::new(vec![1; 4], 0.09, 10000).simulate(
vec![
Chromosome::new_random(equation.coefficients.len(), 0_i32..10, &mut rng),
Chromosome::new_random(equation.coefficients.len(), 0_i32..10, &mut rng),
],
FitnessSelector::from(equation),
&mut rng,
);
assert!(sim_result.is_some())
}