Skip to content

Latest commit

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

🧬 Genetic Algorithm — String Evolution

"Survival of the fittest string." — Charles Darwin, probably, if he coded in Python.

A genetic algorithm that evolves a random population of strings toward a target phrase. No brains required — just selection pressure and a little chaos.


How It Works

1. Population Initialization

1500 random strings are generated, each the same length as the target. Think of it as hiring 1500 monkeys and hoping one of them types Shakespeare.

2. Fitness Evaluation

Each string is scored by counting how many characters match the target at the correct position. A score of len(target) means we're done.

fitness(individual) = Σ (individual[i] == target[i])

3. Roulette Wheel Selection (Fitness-Proportionate Selection)

Parents are selected probabilistically — fitter individuals get a bigger slice of the wheel. The weak still get picked sometimes. Democracy, but rigged.

P(individual) = fitness(individual) / Σ fitness(all)

Cumulative probabilities are built so a single random() roll picks a parent in O(n).

4. Uniform Crossover

Two parents produce two children. For each gene position, a coin flip decides which parent donates. CROSSOVER_PROBABILITY = 1 means a swap always happens on a heads flip.

bit = random(0,1)
child1[i] = parentB[i] if bit == 1 else parentA[i]
child2[i] = parentA[i] if bit == 1 else parentB[i]

5. Mutation

Each gene has a 1% chance of being replaced with a random character from the gene pool. This prevents the population from converging too early and getting stuck in a local optimum — the genetic equivalent of "have you tried turning it off and on again?"


Configuration

ParameterValueWhat it does
POPULATION_POOL_SIZE1500More individuals = more diversity, more compute
MUTATION_RATE0.01Too high → chaos. Too low → stagnation. 1% is the sweet spot
CROSSOVER_PROBABILITY1Always swap on a 1 bit flip (uniform crossover)
NUMBER_OF_INDIVIDUAL_PARENTS2Classic sexual reproduction. Nothing weird
GENE_POOLletters + digits + punctuation + spaceThe alphabet soup your strings are made of

Key Insight

This is a search algorithm disguised as biology. The algorithm never "knows" what the target is — it only knows a fitness score. Given enough generations and selection pressure, it converges. The same principle scales to neural network weight optimization, game AI, and scheduling problems.

The target string is found when best == target. No gradient. No backprop. Just vibes and natural selection.


Run It

python main.py

Watch your population crawl toward enlightenment, one generation at a time.

About

🧬 Teaching 1500 random strings to spell through the power of natural selection. Darwin didn't die for this, but here we are.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages