Solving One-Max for the Last Time

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Understanding and Choosing Genotypes | TOC | Spelling Words with Genetic Algorithms 👉

To get your feet wet with the Problem behaviour you created in this chapter, start small by solving the One-Max problem. You already know what the three problem-specific parameters should look like; all you have to do is fit them into the framework you defined in this chapter.

Open the scripts/one_max.exs file and replace the contents with this:

​ ​defmodule​ OneMax ​do​
​ @behaviour Problem
​ alias Types.Chromosome

​ @impl true
​ ​def​ genotype ​do​
​ genes = for _ <- 1..42, ​do​: Enum.random(0..1)
​ %Chromosome{​genes:​ genes, ​size:​ 42}
​ ​end​

​ @impl true
​ ​def​ fitness_function(chromosome), ​do​: Enum.sum(chromosome.genes)

​ @impl true
​ ​def​ terminate?([best | _]), ​do​: best.fitness == 42
​ ​end​

By now, you should be familiar with these functions, as they are identical to the functions you implemented in your previous attempts at solving the One-Max problem. This time, however, they fit within your problem behaviour.

To run your solution, add the following code below your module definition:

​ soln = Genetic.run(OneMax)

​ IO.write(​"​​\n"​)
​ IO.inspect(soln)

Now, run one_max.exs:

​ ​$ ​​mix​​ ​​run​​…

--

--

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.