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
85
86
87
88
89
90
91
92
93
#![allow(unused)]
#![deny(missing_docs)]

//! # Rust GA
//! 
//! A simple framework for testing genetic algorithms.

mod ga;
/// Module containing Population struct and Genome trait
pub use ga::*;

#[cfg(test)]
mod tests {

    use super::ga::*;

    use rand::Rng;

    fn random() -> f64 {
        rand::thread_rng().gen()
    }

    fn radint(num: usize) -> usize {
        ((num as f64) * random()) as usize
    }

    fn rex(start: usize, end: usize) -> usize {
        start + radint(end - start)
    }

    const TARGET: [char; 20] = ['T', 'o', ' ', 'b', 'e', ',',
        ' ', 'o', 'r', ' ', 'n', 'o', 't', ' ', 't', 'o', ' ', 'b', 'e', '.'];

    use std::iter::once;
    
    fn random_char() -> char {
        (rex(32, 122) as u8) as char
    }

    struct Gene {
        text: [char; 20]
    }

    impl Genome for Gene {
        fn new() -> Self {
            let mut text = [0u8 as char; 20];
            for i in 0..20 {
                text[i] = random_char();
            }
            Self { text }
        }

        fn fitness(&self) -> f64 {
            2f64.powf((0..20).map(|i| ((self.text[i] == TARGET[i]) as usize) as f64).sum())
        }

        fn cross(&self, other: &Self) -> Self {
            let mut text = [0u8 as char; 20];
            for i in 0..20 {
                text[i] = match radint(2) {
                    0 => self.text[i],
                    1 => other.text[i],
                    _ => random_char()
                }
            }

            Self { text }
        }

        fn mutate(mut self) -> Self {
            for i in 0..20 {
                if random() < 0.01 {
                    self.text[i] = random_char();
                }
            }
            self
        }

        fn display(&self) {
            let display_text: String = self.text.iter().cloned().collect();
            println!("{}", display_text);
        }
    }

    #[test]
    fn test_shakespear() {
        let mut population: Population<Gene> = Population::new(100);
        for i in 0..1000 {
            population.live();
            population.next_generation();
        }
    }
}