1use alloc::vec::Vec;
9
10use rand_core::Rng;
11
12use super::{Crossover, Initializer, Mutation};
13use crate::rng::{below, shuffle, two_sorted_indices};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct RandomPermutation {
18 pub n: usize,
20}
21
22impl Initializer<Vec<usize>> for RandomPermutation {
23 fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<usize> {
24 let mut p: Vec<usize> = (0..self.n).collect();
25 shuffle(rng, &mut p);
26
27 p
28 }
29}
30
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
33pub struct Swap;
34
35impl<T> Mutation<Vec<T>> for Swap {
36 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
37 if genome.len() >= 2 {
38 let (i, j) = two_sorted_indices(rng, genome.len());
39 genome.swap(i, j);
40 }
41 }
42}
43
44#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
46pub struct Insertion;
47
48impl<T> Mutation<Vec<T>> for Insertion {
49 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
50 if genome.len() >= 2 {
51 let from = below(rng, genome.len());
52 let item = genome.remove(from);
53 let to = below(rng, genome.len() + 1);
54 genome.insert(to, item);
55 }
56 }
57}
58
59#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
61pub struct Inversion;
62
63impl<T> Mutation<Vec<T>> for Inversion {
64 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
65 if genome.len() >= 2 {
66 let (i, j) = two_sorted_indices(rng, genome.len());
67 genome[i..=j].reverse();
68 }
69 }
70}
71
72#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
74pub struct Scramble;
75
76impl<T> Mutation<Vec<T>> for Scramble {
77 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
78 if genome.len() >= 2 {
79 let (i, j) = two_sorted_indices(rng, genome.len());
80 shuffle(rng, &mut genome[i..=j]);
81 }
82 }
83}
84
85#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
89pub struct Pmx;
90
91impl Crossover<Vec<usize>> for Pmx {
92 fn crossover<R: Rng + ?Sized>(
93 &mut self,
94 a: &Vec<usize>,
95 b: &Vec<usize>,
96 rng: &mut R,
97 ) -> [Vec<usize>; 2] {
98 if a.len() < 2 {
99 return [a.clone(), b.clone()];
100 }
101
102 let (i, j) = two_sorted_indices(rng, a.len());
103
104 [pmx_child(a, b, i, j), pmx_child(b, a, i, j)]
105 }
106}
107
108fn pmx_child(donor: &[usize], filler: &[usize], i: usize, j: usize) -> Vec<usize> {
110 let n = donor.len();
111 let mut child = alloc::vec![usize::MAX; n];
112 let mut position_in_donor = alloc::vec![usize::MAX; n];
113 for (k, &v) in donor.iter().enumerate() {
114 position_in_donor[v] = k;
115 }
116
117 child[i..=j].copy_from_slice(&donor[i..=j]);
118 for k in (0..i).chain(j + 1..n) {
119 let mut value = filler[k];
120 while (i..=j).contains(&position_in_donor[value]) {
122 value = filler[position_in_donor[value]];
123 }
124
125 child[k] = value;
126 }
127
128 child
129}
130
131#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
135pub struct Ox;
136
137impl Crossover<Vec<usize>> for Ox {
138 fn crossover<R: Rng + ?Sized>(
139 &mut self,
140 a: &Vec<usize>,
141 b: &Vec<usize>,
142 rng: &mut R,
143 ) -> [Vec<usize>; 2] {
144 if a.len() < 2 {
145 return [a.clone(), b.clone()];
146 }
147
148 let (i, j) = two_sorted_indices(rng, a.len());
149
150 [ox_child(a, b, i, j), ox_child(b, a, i, j)]
151 }
152}
153
154fn ox_child(donor: &[usize], filler: &[usize], i: usize, j: usize) -> Vec<usize> {
156 let n = donor.len();
157 let mut used = alloc::vec![false; n];
158 let mut child = alloc::vec![usize::MAX; n];
159 for k in i..=j {
160 child[k] = donor[k];
161 used[donor[k]] = true;
162 }
163
164 let mut write = (j + 1) % n;
165 for offset in 0..n {
166 let value = filler[(j + 1 + offset) % n];
167 if !used[value] {
168 child[write] = value;
169 used[value] = true;
170 write = (write + 1) % n;
171 }
172 }
173
174 child
175}
176
177#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
181pub struct Cx;
182
183impl Crossover<Vec<usize>> for Cx {
184 fn crossover<R: Rng + ?Sized>(
185 &mut self,
186 a: &Vec<usize>,
187 b: &Vec<usize>,
188 _rng: &mut R,
189 ) -> [Vec<usize>; 2] {
190 let n = a.len();
191 let mut position_in_a = alloc::vec![0; n];
192 for (k, &v) in a.iter().enumerate() {
193 position_in_a[v] = k;
194 }
195
196 let mut c1 = b.clone();
197 let mut c2 = a.clone();
198 let mut visited = alloc::vec![false; n];
199 let mut take_from_a = true;
200 for start in 0..n {
201 if visited[start] {
202 continue;
203 }
204
205 let mut k = start;
206 while !visited[k] {
207 visited[k] = true;
208 if take_from_a {
209 c1[k] = a[k];
210 c2[k] = b[k];
211 }
212 k = position_in_a[b[k]];
213 }
214
215 take_from_a = !take_from_a;
216 }
217
218 [c1, c2]
219 }
220}
221
222#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
227pub struct EdgeRecombination;
228
229impl Crossover<Vec<usize>> for EdgeRecombination {
230 fn crossover<R: Rng + ?Sized>(
231 &mut self,
232 a: &Vec<usize>,
233 b: &Vec<usize>,
234 rng: &mut R,
235 ) -> [Vec<usize>; 2] {
236 [erx_child(a, b, rng), erx_child(b, a, rng)]
237 }
238}
239
240fn erx_child<R: Rng + ?Sized>(first: &[usize], second: &[usize], rng: &mut R) -> Vec<usize> {
242 let n = first.len();
243 if n < 2 {
244 return first.to_vec();
245 }
246
247 let mut edges: Vec<Vec<usize>> = alloc::vec![Vec::with_capacity(4); n];
248 for tour in [first, second] {
249 for k in 0..n {
250 let (v, next) = (tour[k], tour[(k + 1) % n]);
251 add_edge(&mut edges, v, next);
252 add_edge(&mut edges, next, v);
253 }
254 }
255
256 let mut used = alloc::vec![false; n];
257 let mut child = Vec::with_capacity(n);
258 let mut current = first[0];
259 loop {
260 child.push(current);
261 used[current] = true;
262 for list in &mut edges {
263 list.retain(|&v| v != current);
264 }
265
266 if child.len() == n {
267 return child;
268 }
269
270 current = next_erx_vertex(&edges, &used, current, rng);
271 }
272}
273
274fn add_edge(edges: &mut [Vec<usize>], v: usize, w: usize) {
276 if !edges[v].contains(&w) {
277 edges[v].push(w);
278 }
279}
280
281fn next_erx_vertex<R: Rng + ?Sized>(
284 edges: &[Vec<usize>],
285 used: &[bool],
286 current: usize,
287 rng: &mut R,
288) -> usize {
289 let neighbours = &edges[current];
290 if neighbours.is_empty() {
291 let unused: Vec<usize> = (0..used.len()).filter(|&v| !used[v]).collect();
292 return unused[below(rng, unused.len())];
293 }
294
295 let fewest = neighbours
296 .iter()
297 .map(|&v| edges[v].len())
298 .min()
299 .unwrap_or(0);
300 let candidates: Vec<usize> = neighbours
301 .iter()
302 .copied()
303 .filter(|&v| edges[v].len() == fewest)
304 .collect();
305
306 candidates[below(rng, candidates.len())]
307}
308
309#[must_use]
311pub fn is_permutation(p: &[usize]) -> bool {
312 let mut seen = alloc::vec![false; p.len()];
313 p.iter()
314 .all(|&v| v < seen.len() && !core::mem::replace(&mut seen[v], true))
315}
316
317#[cfg(test)]
318mod tests {
319 use proptest::prelude::*;
320
321 use super::*;
322 use crate::SplitMix64;
323
324 proptest! {
325 #[test]
327 fn operators_keep_permutations(n in 1usize..30, seed in any::<u64>()) {
328 let mut rng = SplitMix64::new(seed);
329 let mut init = RandomPermutation { n };
330 let a = init.initialize(&mut rng);
331 let b = init.initialize(&mut rng);
332 for child in Pmx.crossover(&a, &b, &mut rng)
333 .into_iter()
334 .chain(Ox.crossover(&a, &b, &mut rng))
335 .chain(Cx.crossover(&a, &b, &mut rng))
336 .chain(EdgeRecombination.crossover(&a, &b, &mut rng))
337 {
338 prop_assert!(is_permutation(&child), "{:?}", child);
339 }
340
341 let mut m = a.clone();
342 Swap.mutate(&mut m, &mut rng);
343 Insertion.mutate(&mut m, &mut rng);
344 Inversion.mutate(&mut m, &mut rng);
345 Scramble.mutate(&mut m, &mut rng);
346 prop_assert!(is_permutation(&m));
347 }
348 }
349
350 #[test]
352 fn pmx_textbook_example() {
353 let a = [0, 1, 2, 3, 4, 5, 6, 7, 8];
354 let b = [8, 2, 6, 7, 1, 5, 4, 0, 3];
356 assert_eq!(pmx_child(&a, &b, 3, 6), [8, 2, 1, 3, 4, 5, 6, 0, 7]);
357 }
358
359 #[test]
361 fn cycle_crossover_keeps_positions() {
362 let a = alloc::vec![0, 1, 2, 3, 4, 5, 6, 7, 8];
363 let b = alloc::vec![8, 2, 5, 6, 3, 1, 7, 4, 0];
364 let [c1, c2] = Cx.crossover(&a, &b, &mut SplitMix64::new(0));
365 for k in 0..9 {
366 assert!(c1[k] == a[k] || c1[k] == b[k]);
367 assert!(c2[k] == a[k] || c2[k] == b[k]);
368 }
369
370 assert!(is_permutation(&c1) && is_permutation(&c2));
371 }
372}