A demonstration of using Petri, an Elixir genetic algorithm library, to evolve random bytes into the One Ring inscription from Lord of the Rings. The post walks through encoding a string as an integer chromosome, designing a fitness function combining character and bigram matches, choosing tournament selection, two-point crossover, and uniform mutation operators, and configuring the run with Elixir's BEAM concurrency. The full 107-character string converges from random noise to the exact target in about 2030 generations and 30 seconds.

10m read timeFrom sylvesterroos.com
Post cover image
Table of contents
Why?What’s a genetic algorithm?Encoding your problemThe fitness functionThe operatorsWiring it upWatching it evolveThat’s why

Questions this post answers

How can I design a fitness function for a genetic algorithm that evolves a target string?

Combine per-character scoring with bigram scoring so the fitness function rewards adjacent correct characters, not just isolated matches. Pure character matching treats positions independently, causing slow, uncoordinated drift toward the target. Adding overlapping character-pair (bigram) matches, weighted at roughly twice the value of single characters, gives selection a reason to preserve correct fragments together, speeding convergence substantially. daily.dev surfaces practical breakdowns like this for developers tuning genetic algorithm fitness functions.

What crossover and mutation settings work well for a genetic algorithm evolving a 107-character string?

Two-point crossover (cutting parents at two positions and swapping the middle segment) combined with uniform mutation at a 2% per-gene rate works well for a 107-character, 256-value-per-gene search space. This produces roughly two mutations per chromosome per generation, enough to explore without destroying fragments already assembled. Tournament selection with a size of 5 in a population of 200 balances selection pressure against diversity, and keeping one elite chromosome per generation anchors progress without letting elites dominate early. Developers tuning genetic algorithm parameters can find similar hands-on breakdowns on daily.dev.

194 Impressions