[lab5] Product and mutate operators

This commit is contained in:
Andrew Golovashevich 2026-02-10 10:59:56 +03:00
parent 1f74d15cad
commit 177c11e67c
5 changed files with 40 additions and 0 deletions

3
lab5/src/algo/mod.rs Normal file
View File

@ -0,0 +1,3 @@
mod product;
mod mutate;
mod simulation;

8
lab5/src/algo/mutate.rs Normal file
View File

@ -0,0 +1,8 @@
use rand::Rng;
pub(super) fn mutate(g: &mut [usize], rng: &mut impl Rng) {
let swap_start = rng.random_range(0..(g.len() - 1));
let swap_end = rng.random_range(swap_start..g.len());
g.swap(swap_start, swap_end);
}

27
lab5/src/algo/product.rs Normal file
View File

@ -0,0 +1,27 @@
use rand::Rng;
use std::collections::HashSet;
/**
* OX (Order Crossover)
*/
pub(super) fn product(p1: &[usize], p2: &[usize], out: &mut [usize], rng: &mut impl Rng) {
assert_eq!(p1.len(), p2.len());
assert_eq!(p1.len(), out.len());
let split_start = rng.random_range(0..(p1.len() - 1));
let split_end = rng.random_range(split_start..p1.len());
let used: HashSet<usize> = p1[split_start..split_end].iter().map(|x| *x).collect();
for i in split_start..split_end {
out[i] = p1[i];
}
let mut j = split_end;
for i in 0..p2.len() {
let i = i % p2.len();
if used.contains(&p2[i]) {
continue;
}
out[j % out.len()] = p2[i];
j += 1;
}
}

View File

View File

@ -1 +1,3 @@
mod algo;
fn main() {}