Running Your Solution

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(​"​​ Current Best: "​ <> Integer.to_string(Enum.sum(best)))
 if​ Enum.sum(best) == 1000 ​do
  best
 else
  population
  |> evaluate.()
  |> selection.()
  |> crossover.()
  |> algorithm.(algorithm)
 end
 end

Your 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(​"​​ Answer is "​)
 IO.inspect solution

Here, 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: 982

But 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset