Solving the One-Max Problem Again
Learn how our defined framework can solve the One-Max problem along with seeing a brief overview of what to expect in the next chapter.
We'll cover the following
Applying our framework to the One-Max problem
With our framework built, it’s time to apply it to the One-Max problem. Firstly, open a terminal and create a new file in the scripts directory named one_max.exs
. This has already been done.
Next, open the one_max.exs
file. Now, think about what the framework already accomplishes and what parts of the problem need to be defined. What are the problem-specific parameters needed to pass into run
?
Once the parameters are determined, we’ll start defining them. Logically, the first one is how we encode chromosomes. Remember, for the One-Max problem, we’re looking for the maximum sum of a bitstring of length N
. To keep things consistent, the length should be 1000
. This means the solutions should be bitstrings of length N
.
To define the genotype, add the following at the top of the one_max.exs
file:
genotype = fn -> for _ <- 1..1000, do: Enum.random(0..1) end
This should look similar to what we did in the lesson Introducing the One-Max Problem. All that’s missing is the outside for-loop.
However, recall that the outside for-loop has been taken care of in the initialization step, so it’s unnecessary now.
The next step is to define our fitness function and termination criteria. How did we evaluate solutions in the previous chapter? Remember, we want a maximum sum, so fitness is just the sum. What’s the maximum possible sum we can achieve with a bitstring of length 1000
? Well, that would be 1000
! Therefore, the termination criteria or max_fitness
is 1000
.
Below genotype, define your fitness function and termination criteria like this:
Get hands-on with 1400+ tech skills courses.