Genetic Algorithm Library
A small genetic algorithm in Java: bit-string hypotheses, a one-method fitness interface, single-point crossover and mutation.
This is a simple genetic algorithm implemented in Java. The goal of the project was to create a library, not a whole program. The library implements single point crossover only, but it's very easy to add flawlessly all the other types. The code is distributed under the GNU Public Licence, so you can use it freely — at your own risk of course :).
It was coursework, written with a classmate at AUEB in February 2003, and the archive still carries the assignment's clarifications (resources/dieukriniseis.txt, in Greek written with Latin letters, as one did in 2003): the fitness function can be anything that returns a number, the inputs are integers encoded as bit strings, and the crossover and mutation rates are parameters between 0 and 1. That is the shape of the library.
How it is used
Implement Fitness, which has one method, BigInteger fitness(Hypotheses h). Construct a Genetic with the bit length of a hypothesis, and call ga() with your fitness function, a threshold and a population size; it returns the first hypothesis that scores above the threshold. Hypotheses are BigIntegers, so a bit length is not limited to 32 or 64.
Genetic g = new Genetic(8); // 8-bit hypotheses
g.setCrossoverRate(0.6F); // default 0.5
g.setMutationRate(0.1F); // default 0.5
Hypotheses best = g.ga(myFitness, new BigInteger("30"), 50);TWO_POINT_CROSSOVER and UNIFORM_CROSSOVER are named constants; selecting either prints "not implemented yet", as the first paragraph promised.
Where it stops
Two things, both found by reading the code in 2026 rather than remembered. Selection is not by fitness: each generation sorts the population by probability and then ignores the sorted copy, keeping the first half of the list as it stands, so what actually searches is mutation (and the crossover of neighbours). And the shipped GeneticTest cannot finish, because its fitness function returns 20 for everything and the threshold is 30. I ran it eight times on JDK 26: five runs died with an index error in the first generation or two (the population shrinks from 50 to 48 before it settles) and three ran until I killed them. Give it a real fitness function and a reachable threshold before you trust it with anything.
One of the small utilities (2002–2007); the others are listed there, each with a page like this one.
Downloads
- genetic.zipsource, compiled classes, the test program and the assignment's notes
These are the original files, kept as they were published. Most are decades old and are here as a record rather than as working software.