Solving the One-Max Problem Again

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Understanding Hyperparameters | TOC | What You Learned 👉

With your framework built, it’s time to apply it to the One-Max problem. Open a terminal and create a new file in the scripts directory named one_max.exs, like this:

​ ​$ ​​touch​​ ​​scripts/one_max.exs​

Open the one_max.exs file. Now, think about what your framework already accomplishes for you and what parts of the problem you need to define. What are the problem-specific parameters you need to pass into run?

Once you determine what these parameters are, you’ll need to start defining them. Logically, the first one is how you encode chromosomes. Remember, for the One-Max problem, you’re looking for the maximum sum of a bitstring of length N. To keep things consistent, your length should be 1000. This means your solutions should be bitstrings of length N.

To define your genotype, at the top of the one_max.exs file, add the following:

​ genotype = ​fn​ -> for _ <- 1..1000, ​do​: Enum.random(0..1) ​end​

This should look similar to what you did in Chapter 1, Writing Your First Genetic Algorithm. All that’s missing is the outside for-loop. However, if you recall, the outside for-loop is taken care of for you in the initialization step, so it’s unnecessary now.

--

--

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.