commit 8f4c4c86c881b56dcc172adb0bf8319b2a39a976
parent 3c4ced55bea0942d233b986d68e4eb2dcf5227f0
Author: dracuxan <[email protected]>
Date: Fri, 3 Apr 2026 12:11:00 +0530
upd
Diffstat:
4 files changed, 37 insertions(+), 16 deletions(-)
diff --git a/genetic/scripts/cargo.exs b/genetic/scripts/cargo.exs
@@ -11,16 +11,29 @@ defmodule Cargo do
@impl true
def fitness_function(chromosome) do
profits = [6, 5, 8, 9, 6, 7, 3, 1, 2, 6]
+ weights = [10, 6, 8, 7, 10, 9, 7, 11, 6, 8]
+ weight_limit = 40
+ potential_profits =
+ profits
+ |> Enum.zip(chromosome.genes)
+ |> Enum.map(fn {p, g} -> p * g end)
+ |> Enum.sum()
+
+ over_limit? =
+ weights
+ |> Enum.zip(chromosome.genes)
+ |> Enum.map(fn {w, g} -> w * g end)
+ |> Enum.sum()
+ |> Kernel.>(weight_limit)
+
+ profits = if over_limit?, do: 0, else: potential_profits
profits
- |> Enum.zip(chromosome.genes)
- |> Enum.map(fn {p, g} -> p * g end)
- |> Enum.sum()
end
@impl true
- def terminate?(population) do
- Enum.max_by(population, &Cargo.fitness_function/1).fitness == 53
+ def terminate?(_population, generation) do
+ generation == 100
end
end
diff --git a/genetic/scripts/one_max.exs b/genetic/scripts/one_max.exs
@@ -4,8 +4,8 @@ defmodule OneMax do
@impl true
def genotype do
- genes = Enum.map(1..1000, fn _ -> Enum.random(0..1) end)
- %Chromosome{genes: genes, size: 1000}
+ genes = Enum.map(1..30, fn _ -> Enum.random(0..1) end)
+ %Chromosome{genes: genes, size: 30}
end
@impl true
@@ -14,8 +14,22 @@ defmodule OneMax do
end
@impl true
- def terminate?([best | _]) do
- best.fitness == 1000
+ def terminate?(_population, generation) do
+ # best = Enum.max_by(population, &OneMax.fitness_function/1)
+ # best.fitness == 30
+
+ # best = Enum.min_by(population, &OneMax.fitness_function/1)
+ # best.fitness == 0
+
+ # avg =
+ # population
+ # |> Enum.map(&Enum.sum(&1.genes))
+ # |> Enum.sum()
+ # |> Kernel./(length(population))
+ #
+ # avg >= 15
+
+ generation == 100
end
end
diff --git a/genetic/scripts/speller.exs b/genetic/scripts/speller.exs
@@ -19,7 +19,7 @@ defmodule Speller do
end
@impl true
- def terminate?(population) do
+ def terminate?(population, _generation) do
[best | _] = population
best.fitness == 1
end
diff --git a/genetic/test/genetic_test.exs b/genetic/test/genetic_test.exs
@@ -1,8 +1,2 @@
defmodule GeneticTest do
- use ExUnit.Case
- doctest Genetic
-
- test "greets the world" do
- assert Genetic.hello() == :world
- end
end