Trait FitnessIndividualTrait

Source
pub trait FitnessIndividualTrait: EachCrateIndividual {
    // Required method
    fn fitness(&self, other: &Self) -> usize;

    // Provided method
    fn fitness_group<'a, G>(group: G) -> HashMap<usize, usize>
       where G: IntoIterator<Item = &'a Self>,
             Self: 'a { ... }
}
Expand description

A trait for a individual having a method for assigning a fitness score to a individual.

The process corresponds the “Fitness” step of GroupTrait.

§Example

use std::{collections::HashMap, rc::Rc};

use scarlet_queen_core::{Individual, EachCrateIndividual, FitnessIndividualTrait};

struct Fitness(Rc<Individual<u8>>);

impl EachCrateIndividual for Fitness {
    type Item = u8;

    fn new(individual: &std::rc::Rc<Individual<u8>>) -> Self {
        Fitness(Rc::clone(individual))
    }

    fn get_individual(&self) -> &Individual<u8> {
        &self.0
    }
}

impl FitnessIndividualTrait for Fitness {
    fn fitness(&self, other: &Self) -> usize {
        if self.get_value() >= other.get_value() {
            1
        } else {
            0
        }
    }
}

let r_1: Rc<Individual<u8>> = Rc::new(Individual::new_with_id(0, 13));
let sample_1: Fitness = Fitness::new(&r_1);

assert_eq!(sample_1.get_individual(), r_1.as_ref());
assert_eq!(sample_1.get_id(), 0usize);
assert_eq!(sample_1.get_value(), &13u8);

let sample_2: Fitness = Fitness::new(&Rc::new(Individual::new_with_id(1, 5)));

assert_eq!(sample_1.fitness(&sample_2), 1);

let sample: Vec<Fitness> = vec![
    sample_1,
    sample_2,
    Fitness::new(&Rc::new(Individual::new_with_id(2, 15)))
];

assert_eq!(Fitness::fitness_group(&sample), vec![(0usize, 1usize), (1, 0), (2, 2)].into_iter().collect::<HashMap<usize, usize>>());

Required Methods§

Source

fn fitness(&self, other: &Self) -> usize

Calculate a fitness score to an other individual.

  • other - A target of fitness.

Provided Methods§

Source

fn fitness_group<'a, G>(group: G) -> HashMap<usize, usize>
where G: IntoIterator<Item = &'a Self>, Self: 'a,

Calculate a fitness to a group.

A fitness score to a group is the sum of fitness scores to other individuals of the group.

The elements of group must be assigned a number to.

  • 'a - A lifetime of group.
  • G - A type of group.
  • group - A value which you are able to get Self from.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§