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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//! Unique chromosome initializer.
//!
//! Creates a full permutation of [`UniqueGenotype<T>`](crate::genotypes::UniqueGenotype)
//! genes for [`UniqueChromosome`](crate::chromosomes::UniqueChromosome) chromosomes.
//! Uses Fisher-Yates shuffling so the result is a uniformly random permutation of the
//! alphabet — no duplicate genes, all alphabet elements present.
use crateUniqueGenotype;
use Rng;
use Debug;
/// Randomly initializes a chromosome's DNA as a full permutation of the given alphabet.
///
/// Uses Fisher-Yates shuffle to produce a uniformly random permutation. The returned
/// `Vec` has the same length as `alphabet` — every element appears exactly once.
///
/// This is the canonical initializer for [`UniqueChromosome<T>`](crate::chromosomes::UniqueChromosome).
/// Pass it via `with_initialization_fn`:
///
/// ```rust,no_run
/// // no_run: API illustration — Ga requires full configuration to build
/// use genetic_algorithms::ga::Ga;
/// use genetic_algorithms::initializers::unique_random_initialization;
///
/// let alphabet: Vec<i32> = (0..15).collect();
/// // let ga = Ga::new()
/// // .with_initialization_fn({
/// // let alphabet = alphabet.clone();
/// // move |_n, _| unique_random_initialization(&alphabet)
/// // })
/// // // ...
/// // .build()?;
/// ```
///
/// # Arguments
///
/// * `alphabet` - The set of values to permute. An empty slice returns an empty `Vec`.
///
/// # Returns
///
/// A `Vec<UniqueGenotype<T>>` of length `alphabet.len()` representing a random permutation.
/// Each gene's `id` is set to the original position of the value in the shuffled index array.
///
/// # Examples
///
/// ```
/// use genetic_algorithms::initializers::unique_random_initialization;
///
/// let alphabet = vec![10, 20, 30, 40, 50];
/// let dna = unique_random_initialization(&alphabet);
/// assert_eq!(dna.len(), 5);
///
/// // All alphabet elements are present exactly once.
/// let mut values: Vec<i32> = dna.iter().map(|g| g.value).collect();
/// values.sort();
/// assert_eq!(values, vec![10, 20, 30, 40, 50]);
/// ```