the-comfy-coder
Guess that Sentence! (Genetic Algorithm)
The full code can be found on my GitHub
The Project
The goal of this exercise is to make a genetic algorithm that can guess a target string. I will be using the following quote from The Hobbit: “If more of us valued food and cheer and song above hoarded gold it would be a merrier world “
Organism Class Methods
Organism
This method generates a new organism object. It takes the goal string and makes a guess “value” string by randomly creating a string of the same length. There is also a constructor that just takes the goal string and a value string. Both goalString and value are class variables.



Fitness
This method determines the fitness level of an organism, based on the number of characters that match the goal string.
Mate
This method mates two organisms, creating two offspring returned in a list. The crossover point is randomly generated to be number between 1 and one less than the goal string length. The two child organisms are made by crossing over each parent at the point.


Compare To
This method overrides the compareTo method for Organisms so that they are compared by their fitness levels.
Mutate
This method mutates a string based on the mutation probability given by the user. This creates a probability of characters changing to other characters, in hopes that the target string is found.
I have also modified the toString method to display organism data.

Population Class Methods
Population
This method creates a new population, setting the goalString, mutation probability, number of generations, and population size based on given input. The current generation is then created as a list of organisms, which are randomly generated to begin with.


Iterate
This method goes through all of the generations, either until you run out of generations or the goal string is found. For each generation, the most fit organism is allowed to mate with all other organisms in the population.
Main
This method allows the user to chose a string to guess, the number of organisms in each generation, number of generations, and the mutation probability. The algorithm runs until either the number of generations is met or until the goal string is found, whichever comes first.

Recent Comments