commit 705c945e2d0944241a120ef7245b74092dda4adb
Author: dracuxan <[email protected]>
Date: Sat, 28 Mar 2026 18:12:19 +0530
new: one max solution
Diffstat:
1 file changed, 61 insertions(+), 0 deletions(-)
diff --git a/scripts/one_max.exs b/scripts/one_max.exs
@@ -0,0 +1,61 @@
+population =
+ for _ <- 1..100 do
+ for _ <- 1..1000 do
+ Enum.random([1, 0])
+ end
+ end
+
+evaluate =
+ fn population ->
+ Enum.sort_by(population, &Enum.sum/1, :desc)
+ 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_split = :rand.uniform(1000)
+
+ {{h1, t1}, {h2, t2}} =
+ {Enum.split(p1, cx_split), Enum.split(p2, cx_split)}
+
+ [h1 ++ t2, h2 ++ t1 | acc]
+ end)
+ end
+
+mutation =
+ fn population ->
+ Enum.map(population, fn chromosome ->
+ if :rand.uniform() < 0.05 do
+ Enum.shuffle(chromosome)
+ else
+ chromosome
+ end
+ end)
+ end
+
+algorithm =
+ fn population, algorithm ->
+ best = Enum.max_by(population, &Enum.sum/1)
+ IO.write("\rcurrent best: " <> Integer.to_string(Enum.sum(best)))
+
+ if Enum.sum(best) == 1000 do
+ best
+ else
+ population
+ |> evaluate.()
+ |> selection.()
+ |> crossover.()
+ |> mutation.()
+ |> algorithm.(algorithm)
+ end
+ end
+
+sol = algorithm.(population, algorithm)
+IO.puts("\nfinal answer: #{inspect(sol)}")