~ruther/ctu-fee-eoa

ref: dfddcfde9cade6fd94ace5bca2f846f48c230e3c ctu-fee-eoa/env/src/fitness/labs.rs -rw-r--r-- 1.2 KiB
dfddcfde — Rutherther chore: split types and functions to separate module files a day ago
                                                                                
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
use std::convert::Infallible;
use crate::{binary_string::BinaryString, test_infra::load_test_file};
use super::FitnessFunction;

pub struct LABS;

impl LABS {
    fn new() -> Self {
        LABS
    }

    fn Ck(k: usize, S: &Vec<i32>) -> i32 {
        let D = S.len();
        S.iter()
            .take(D - k)
            .zip(S.iter().skip(k))
            .map(|(x, y)| x * y)
            .sum()
    }
}

impl FitnessFunction for LABS {
    type In = BinaryString;
    type Out = i32;
    type Err = Infallible;

    fn fit(self: &Self, chromosome: &BinaryString) -> Result<i32, Infallible> {
        let S: Vec<i32> = chromosome
            .into_iter()
            .map(|c| (*c as i32) * 2 - 1)
            .collect();
        let D = S.len();

        Ok((1..=D-1)
           .map(|k| LABS::Ck(k, &S).pow(2))
           .sum())
    }
}

#[test]
fn test_LABS() {
    let data = load_test_file::<i8, i32>("tests/labs.txt");

    for test in data {
        println!("Test vector {}", test.inp.iter()
            .map(|x| x.to_string())
            .collect::<Vec<String>>()
            .join(", "));
        assert_eq!(
            LABS::new().fit(&BinaryString::new(test.inp)).unwrap(),
            test.out
        )
     }
}