commit 3c4ced55bea0942d233b986d68e4eb2dcf5227f0
parent 7bb5ee8d7422377810512633f15fb4b8ecfe1439
Author: dracuxan <[email protected]>
Date: Fri, 3 Apr 2026 10:57:13 +0530
new: add generation as terminating criteria
Diffstat:
2 files changed, 9 insertions(+), 6 deletions(-)
diff --git a/genetic/lib/genetic.ex b/genetic/lib/genetic.ex
@@ -5,7 +5,7 @@ defmodule Genetic do
population = initialize(&problem.genotype/0)
population
- |> evolve(problem, opts)
+ |> evolve(problem, 0, opts)
end
def initialize(genotype, opts \\ []) do
@@ -39,7 +39,8 @@ defmodule Genetic do
{{h1, t1}, {h2, t2}} =
{Enum.split(p1.genes, cx_point), Enum.split(p2.genes, cx_point)}
- {c1, c2} = {%Chromosome{p1 | genes: h1 ++ t2}, %Chromosome{p2 | genes: h2 ++ t1}}
+ {c1, c2} =
+ {%Chromosome{p1 | genes: h1 ++ t2, age: 0}, %Chromosome{p2 | genes: h2 ++ t1, age: 0}}
[c1, c2 | acc]
end
@@ -57,19 +58,21 @@ defmodule Genetic do
end)
end
- def evolve(population, problem, opts \\ []) do
+ def evolve(population, problem, generation, opts \\ []) do
population = evaluate(population, &problem.fitness_function/1, opts)
best = hd(population)
IO.write("\rcurrent best: #{best.fitness}")
- if problem.terminate?(population) do
+ if problem.terminate?(population, generation) do
best
else
+ generation = generation + 1
+
population
|> select(opts)
|> crossover(opts)
|> mutation(opts)
- |> evolve(problem, opts)
+ |> evolve(problem, generation, opts)
end
end
end
diff --git a/genetic/lib/problem.ex b/genetic/lib/problem.ex
@@ -3,5 +3,5 @@ defmodule Problem do
@callback genotype :: Chromosome.t()
@callback fitness_function(Chromosome.t()) :: number()
- @callback terminate?(Enum.t()) :: boolean()
+ @callback terminate?(Enum.t(), integer()) :: boolean()
end