moonlander-gp 0.1.1

Genetic Programming framework providing AST abstraction and evolution routines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use rand::Rng;
use super::fitness::Fitness;
use super::super::AstNode;
use super::super::Population;

/// Return the winner from a tournament of size N, randomly picked from the scored population.
pub fn tournament_selection<'a, P, F>(tournament_size: usize, pop: &'a Population<P, F>, rng: &mut Rng) -> &'a P
    where P: AstNode+Clone+Sync,
          F: Fitness+Send
{
    // Generate N random indexes. Slightly faster than rand::sample(), don't care about
    // the inaccuracy introduced by sampling with replacement.
    let count = pop.n();
    let candidate_indexes = (0..tournament_size).map(|_| rng.next_u64() as usize % count);

    let (_, winner_i) = candidate_indexes.map(|i| (&pop.scores[i], i)).max_by_key(|f| f.0.score_card()).unwrap();
    &pop.population[winner_i]
}