Selecting Parents

Genetic Algorithms in Elixir — by Sean Moriarity (14 / 101)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Understanding the Flow of Genetic Algorithms | TOC | Creating Children 👉

You now have a list of chromosomes sorted by sum. You want to produce parents for reproduction. This step is referred to as selection. Selection is the process of picking the parents that will be combined to create new solutions. The goal of selection is to pick some parents that can easily be combined to create better solutions.

For this step, you’ll want the result of the selection function to be formatted nicely for crossover. Your selection function should return a list of tuples consisting of a pair of parents to be combined. Inside the selection function, add the following:

​ selection =
​ ​fn​ population ->
​ population
​ |> Enum.chunk_every(2)
​ |> Enum.map(&List.to_tuple(&1))
​ ​end​

In this function, you use Enum.chunk_every/2 to create a list of pairs. These pairs are parents that are selected for combination in the crossover step. Sometimes, the population you’re working with isn’t necessarily a friendly number like 100. You can also use Enum.chunk_every/3 and tell Elixir what to do with the leftover elements in your list.

The result of Enum.chunk_every/2 is passed to Enum.map/2, which iterates over the list and transforms the values using List.to_tuple/1. This function transforms the list of lists to a list of tuples. This is done because tuples are…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.