Summary Files Commits Branches @commit @diff @stats
path: root / Year 4 / Artificial Intelligence / hw03 / src / main.rs
blob: 49a86240b8dd4123f00c38381c0816ee04ea905d (plain) (blame)
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
#![allow(non_snake_case)]
use std::fmt;
use text_io::{read};

mod generation;
use generation::Generation;
mod gene;
use gene::Gene;
mod chromosome;

impl fmt::Display for Generation {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let best = self.population
            .iter()
            .min_by(|a, b| a.fitness.partial_cmp(&b.fitness).unwrap())
            .unwrap();
        for cityi in &best.genes[..best.genes.len()-1] {
            let curr = &self.map[*cityi];
            if curr.name.is_empty() {
                write!(f, "({},{}) -> ", curr.x, curr.y)?;
            }
            else {
                write!(f, "{} -> ", curr.name)?;
            }
        }

        let last = &self.map[*best.genes.last().unwrap()];
        if last.name.is_empty() {
            writeln!(f, "({},{})", last.x, last.y)?;
        }
        else {
            writeln!(f, "{}", last.name)?;
        }

        writeln!(f, "{}", best.fitness)
    }
}

fn main() {
    let mut G: Generation;
    let input: String = read!();
    let N = input.parse::<usize>();

    if N.is_ok() {
        let N = N.unwrap();
        G = Generation::new_from_random(N);
    }
    else {
        let names: Vec<String> = std::fs::read_to_string([input.clone(), "_name.csv".to_string()].concat())
            .expect("Couldn't open points file: ..._name.csv")
            .lines()
            .map(|x| x.to_string())
            .collect();
        let points: Vec<Gene> = std::fs::read_to_string([input, "_xy.csv".to_string()].concat())
            .expect("Couldn't open points file: ..._xy.csv")
            .lines()
            .enumerate()
            .map(|(i, l)| {
                let coords: Vec<&str> = l.split(',').collect();
                Gene {
                    x: coords[0].parse::<f64>().unwrap(),
                    y: coords[1].parse::<f64>().unwrap(),
                    name: names[i].clone(),
                }
            })
            .collect();
        G = Generation::new_from_map(points);
    }

    println!("{}", G.best_fitness());
    let mut i = 0;

    while ! G.terminated() {
        if i < 8 {
            println!("{}", G.best_fitness());
            i += 1;
        }
        G.selection_crossover();
        G.mutate();
        G = G.next_generation();
    }

    println!("");
    println!("{}", G);

    /* For debugging */
    // let best = G.population
    //     .iter()
    //     .min_by(|a, b| a.fitness.partial_cmp(&b.fitness).unwrap())
    //     .unwrap();
    // println!("{} {}", best.genes.first().unwrap(), best.genes.last().unwrap());
}