-
Notifications
You must be signed in to change notification settings - Fork 0
/
uniform_crossover.rs
36 lines (30 loc) · 1.21 KB
/
uniform_crossover.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
use rand::{Rng, thread_rng, distributions::Bernoulli, prelude::Distribution};
use rayon::iter::ParallelIterator;
use rayon::prelude::ParallelSliceMut;
use crate::{Crossover, Individual};
use crate::crossover::UniformCrossover;
use crate::population::Int;
impl Crossover<Int> for UniformCrossover {
fn crossover(&self, population: &mut Vec<Int>) {
let distribution = Bernoulli::new(self.toss_probability).unwrap();
population.par_chunks_mut(2).for_each_init(
|| thread_rng(),
|mut rng, chunk| {
if rng.gen_bool(self.crossover_rate) {
let mut parent1 = chunk[0].clone();
let mut parent2 = chunk[1].clone();
let len = parent1.get_chromosome().len();
for i in 0..len {
if distribution.sample(&mut rng) {
let temp = parent1.get_gene(i);
parent1.set_gene(i, parent2.get_gene(i));
parent2.set_gene(i, temp);
}
}
chunk[0] = parent1;
chunk[1] = parent2;
}
},
)
}
}