extern crate rsgenetic;
extern crate rand;
use rsgenetic::sim::*;
use rsgenetic::sim::seq::Simulator;
use rsgenetic::sim::select::*;
use rsgenetic::pheno::*;
use rand::distributions::{IndependentSample, Range};
struct MyData {
x: f64,
}
impl Phenotype for MyData {
fn fitness(&self) -> f64 {
10.0 - ((self.x + 3.0) * (self.x + 3.0))
}
fn crossover(&self, other: &MyData) -> MyData {
MyData {
x: (self.x + other.x) / 2.0
}
}
fn mutate(&self) -> MyData {
let between = Range::new(-1.0, 1.0);
let mut rng = rand::thread_rng();
let offset = between.ind_sample(&mut rng);
MyData {
x: self.x + offset
}
}
}
impl Clone for MyData {
fn clone(&self) -> MyData {
MyData { x: self.x }
}
}
fn main() {
let population = (-300..300).map(|i| MyData{ x: i as f64 }).collect();
let mut s = Simulator::builder()
.set_population(&population)
.set_selector(Box::new(StochasticSelector::new(10)))
.set_max_iters(50)
.build();
s.run();
let result = s.get().unwrap();
let time = s.time();
println!("Execution time: {} ns.", time.unwrap());
println!("Expected result: (-3, 10).");
println!("Result: ({}, {}).", result.x, result.fitness());
}