Running Your Solution
Genetic Algorithms in Elixir — by Sean Moriarity (16 / 101)
👈 Creating Children | TOC | Adding Mutation 👉
Your genetic algorithm will now look something like this:
population = for _ <- 1..100, do: for _ <- 1..1000, do: Enum.random(0..1)
evaluate =
fn population ->
Enum.sort_by(population, &Enum.sum/1, &>=/2)
end
selection =
fn population ->
population
|> Enum.chunk_every(2)
|> Enum.map(&List.to_tuple(&1))
end
crossover =
fn population ->
Enum.reduce(population, [],
fn {p1, p2}, acc ->
cx_point = :rand.uniform(1000)
{{h1, t1}, {h2, t2}} =
{Enum.split(p1, cx_point),
Enum.split(p2, cx_point)} [h1 ++ t2, h2 ++ t1 | acc]
end
)
end
algorithm =
fn population, algorithm ->
best = Enum.max_by(population, &Enum.sum/1)
IO.write("\rCurrent Best: " <> Integer.to_string(Enum.sum(best)))
if Enum.sum(best) == 1000 do
best
else
population
|> evaluate.()
|> selection.()
|> crossover.()
|> algorithm.(algorithm)
end
endYour algorithm now has all of the necessary components it needs to produce a solution; however, you might be wondering why the mutation step was left out. You’ll find out in a minute — before then, try running your algorithm to ensure that everything works correctly.
Remember, the algorithm function takes a population and a reference to itself as input. Additionally, remember that it returns a solution when a maximum sum of 1000 is achieved. Add the following lines to the end of the one_max.exs file:
solution = algorithm.(population, algorithm)
IO.write("\n Answer is \n")
IO.inspect solutionHere, you assign the result of the completed algorithm (that is, the solution) to a variable named solution. You then output some text to the screen to show what your algorithm has come up with.
Next, go back to your terminal and navigate to the scripts folder. Then run the following command:
$ elixir one_max.exs
Current Best: 982But wait, what’s going on here? Why is the algorithm stopping on a best fitness below 1000? It’s likely that, no matter how many times you run it, the algorithm’s improvement will almost certainly slow near 1000. You may even find it difficult for the problem to ever reach 1000. The problem is premature convergence.
👈 Creating Children | TOC | Adding Mutation 👉
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.

