Mutation and reproduction

Before we discuss competition between two Individuals, let's talk about mutation and reproduction. Mutation is the easier of the two to understand, in my opinion, because it operates on one Individual at a time. Our implementation:

    pub fn mutate(&mut self, mutation_chance: u32, core_size: u16) -> () {
        self.chromosome.par_iter_mut().for_each(|gene| {
            if thread_rng().gen_weighted_bool(mutation_chance) {
                *gene = if thread_rng().gen::<bool>() {
                    Some(Instruction::random(core_size))
                } else {
                    None
                };
            }
        });
    }

The call to par_iter_mut creates a ParallelIterator in which the elements of the iterator are mutable, much like iter_mut from the standard library. The for_each operator applies the closure to each. The for_each

Get Hands-On Concurrency with Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.