genetic

genetic algorithm framework
git clone igris.git:dracuxan/genetic.git
Log | Files | Refs | README

commit e700eba136d4dabc9a9bbe120247e78bb2f913b5
parent 9a8057c89c98eb8cc4398b412a4c7b7f253ae381
Author: dracuxan <[email protected]>
Date:   Wed,  8 Apr 2026 14:04:37 +0530

problem: breaking xor cipher

Diffstat:
Agenetic/scripts/codebreaker.exs | 46++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 46 insertions(+), 0 deletions(-)

diff --git a/genetic/scripts/codebreaker.exs b/genetic/scripts/codebreaker.exs @@ -0,0 +1,46 @@ +defmodule Codebreaker do + alias Types.Chromosome + @behaviour Problem + @max_n 64 + import Bitwise + + def genotype do + genes = Enum.map(1..@max_n, fn _ -> Enum.random(0..1) end) + %Chromosome{genes: genes, size: @max_n} + end + + def fitness_function(chromosome) do + target = "ILoveGeneticAlgorithms" + encrypted = "LIjs`B`k`qlfDibjwlqmhv" + + cypher = fn word, key -> + word + |> to_charlist() + |> Enum.map(fn x -> rem(bxor(x, key), 32768) end) + end + + key = + chromosome.genes + |> Enum.map(&Integer.to_string(&1)) + |> Enum.join("") + |> String.to_integer(2) + + guess = List.to_string(cypher.(encrypted, key)) + String.jaro_distance(target, guess) + end + + def terminate?(population, _generation) do + best = hd(population) + best.fitness == 1 + end +end + +{soln, _} = Genetic.run(Codebreaker, crossover_type: &Toolbox.Crossover.single_point/3) + +{key, ""} = + soln.genes + |> Enum.map(&Integer.to_string(&1)) + |> Enum.join("") + |> Integer.parse(2) + +IO.puts("\nThe key is #{key}")