Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Random;
- /**
- * My basic genetic algorithm PoC code.
- * Commented for dads sake
- * @author Jorde Kang <jorde@protonmail.ch>
- */
- public class Genetic {
- private int generationSize; // The size of the generations
- private String genes; // The genepool to be used in mutations
- private String solution; // The answer the population is aiming for
- private ArrayList<String> population; // An array of strings containing the population
- private Random rand; // A random number generator
- private int generations; // The number of generations simulated so far
- /**
- * Constructor for objects of class Genetic
- * @param String solution
- * @param int generationSize
- */
- public Genetic(String solution, int generationSize)
- {
- genes = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Assigning the value of 'genes' to the latin alphabet
- this.solution = solution; // Setting the solution to the one given in the parameter
- population = new ArrayList<String>(); // Initialising the array to store the population
- rand = new Random(); // Initialising the random number generator
- this.generationSize = generationSize; // Setting the generation size to the one given in the parameter
- initialPopulation(); // Generating the initial population
- generations = 1;
- while(true){ // Simulate more generations indefinitely until the answer is produced
- nextGeneration(getBest());
- }
- }
- /**
- * Generates the initial population as a set of random strings at the length of the solution
- */
- public void initialPopulation()
- {
- while(population.size() < generationSize) {
- String newChild = ""; // initialises the string
- for (int i=0;i < solution.length();i++) { // iterate for the length of the solution
- newChild = newChild+genes.charAt(rand.nextInt(52)); // Sets the character to a random letter from the gene pool
- }
- population.add(newChild); // Add the new child to the population
- }
- }
- /**
- * Calculates the fitness of a given string
- * @param String str
- */
- public int getFitness(String str)
- {
- int numCorrect=0;
- for (int i=0;i<str.length();i++) {
- if (str.charAt(i) == solution.charAt(i)) { // Check if the letter is correct
- numCorrect++; // Add it to the fitness score
- }
- }
- return numCorrect;
- }
- /**
- * Mutates the given string
- * @param String str
- */
- public String mutate(String str)
- {
- StringBuilder builder = new StringBuilder(str); // Strings are immutable in Java, a StringBuilder must be used to change them
- builder.setCharAt(rand.nextInt(str.length()), genes.charAt(rand.nextInt(genes.length()))); // Set a random letter from the string to a random letter from the gene pool
- return builder.toString(); // Return the created string
- }
- /**
- * Gets the fittest from the last generation
- */
- public String getBest()
- {
- generations++; // incrememnts the number of generations
- String best = population.get(0); // sets the best to the first as default
- for(String x : population) // For each string in the populatio
- {
- if (getFitness(x) > getFitness(best)) { // Check if it is the fittest
- best = x; // Set it as the best
- }
- }
- System.out.println("Best of Generation "+generations+" : "+best); // Print who is the best
- population.clear(); // Reset the population ready for the next generation
- return best;
- }
- /**
- * Simulates a new generation based on the strongest from the last
- */
- public void nextGeneration(String best)
- {
- for (int i=0;i < generationSize; i++) { // Iterate until we reach the assigned generation size
- String newString = mutate(best); // Mutate the best from before
- population.add(newString); // Add it to the population
- if (newString.equals(solution)){ // If it is the solution
- System.out.println("SOLUTION FOUND: "+newString); // Say so
- System.exit(0); // and quit
- }
- }
- }
- /**
- * Main function
- * Mainly handling command line arguments, you can ignore.
- */
- public static void main(String[] args)
- {
- try {
- int num = Integer.parseInt(args[1]);
- new Genetic(args[0], num);
- }
- catch(ArrayIndexOutOfBoundsException ex)
- {
- System.err.println("Please provide 2 arguments, the target string and the size of the generations to simulate.");
- System.exit(1);
- }
- catch (NumberFormatException e) {
- System.err.println("Second argument was not an integer.");
- System.exit(1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement