Selecting Parents
Genetic Algorithms in Elixir — by Sean Moriarity (14 / 101)
👈 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))
endIn 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 much easier to work with in the next step.
Notice how the last two steps have created pairs of parents of approximately equal fitness. The list is sorted by the maximum sum in descending order. This means that the selection function will automatically pair more fit chromosomes with other fit chromosomes and vice versa with unfit chromosomes. This isn’t always the best strategy, but you’ll learn more about this in Chapter 5, Selecting the Best.
👈 Understanding the Flow of Genetic Algorithms | TOC | Creating Children 👉
Genetic Algorithms in Elixir by Sean Moriarity can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.






