From dd037eb96833637e2ec2bb9bec824c71981ef67e Mon Sep 17 00:00:00 2001 From: Rutherther Date: Sat, 1 Nov 2025 10:24:33 +0100 Subject: [PATCH] feat(tsp): add move node perturbation --- codes/tsp_hw01/src/tsp.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/codes/tsp_hw01/src/tsp.rs b/codes/tsp_hw01/src/tsp.rs index a4c6d39a31f54ad072ed979d58384e18bbd9f2c4..1f4eb6c15dd6b84afea07f8a5f52f3a359e9fe7f 100644 --- a/codes/tsp_hw01/src/tsp.rs +++ b/codes/tsp_hw01/src/tsp.rs @@ -240,6 +240,44 @@ where } } +pub struct MovePerturbation { + _phantom: PhantomData +} + +impl MovePerturbation { + pub fn new() -> Self { + Self { _phantom: PhantomData } + } +} + +impl PerturbationOperator for MovePerturbation +where + D: Dim, + DefaultAllocator: Allocator, + DefaultAllocator: Allocator, +{ + type Chromosome = NodePermutation; + + fn perturb(&self, chromosome: &mut Self::Chromosome, rng: &mut dyn RngCore) { + let from = rng.random_range(0..chromosome.permutation.len()); + let to = rng.random_range(0..chromosome.permutation.len()); + + let element = chromosome.permutation[from]; + + if from < to { + for i in from..to { + chromosome.permutation[i] = chromosome.permutation[i + 1]; + } + } else { + for i in (to+1..=from).rev() { + chromosome.permutation[i] = chromosome.permutation[i - 1]; + } + } + + chromosome.permutation[to] = element; + } +} + pub struct SwapPerturbation { _phantom: PhantomData }