Advertisement
Guest User

Untitled

a guest
May 20th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.52 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Random;
  3.  
  4. /**
  5. * My basic genetic algorithm PoC code.
  6. * Commented for dads sake
  7. * @author Jorde Kang <jorde@protonmail.ch>
  8. */
  9. public class Genetic {
  10.  
  11. private int generationSize; // The size of the generations
  12. private String genes; // The genepool to be used in mutations
  13. private String solution; // The answer the population is aiming for
  14. private ArrayList<String> population; // An array of strings containing the population
  15. private Random rand; // A random number generator
  16. private int generations; // The number of generations simulated so far
  17.  
  18. /**
  19. * Constructor for objects of class Genetic
  20. * @param String solution
  21. * @param int generationSize
  22. */
  23. public Genetic(String solution, int generationSize)
  24. {
  25. genes = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Assigning the value of 'genes' to the latin alphabet
  26. this.solution = solution; // Setting the solution to the one given in the parameter
  27. population = new ArrayList<String>(); // Initialising the array to store the population
  28. rand = new Random(); // Initialising the random number generator
  29. this.generationSize = generationSize; // Setting the generation size to the one given in the parameter
  30. initialPopulation(); // Generating the initial population
  31. generations = 1;
  32. while(true){ // Simulate more generations indefinitely until the answer is produced
  33. nextGeneration(getBest());
  34. }
  35. }
  36.  
  37. /**
  38. * Generates the initial population as a set of random strings at the length of the solution
  39. */
  40. public void initialPopulation()
  41. {
  42. while(population.size() < generationSize) {
  43. String newChild = ""; // initialises the string
  44. for (int i=0;i < solution.length();i++) { // iterate for the length of the solution
  45. newChild = newChild+genes.charAt(rand.nextInt(52)); // Sets the character to a random letter from the gene pool
  46. }
  47. population.add(newChild); // Add the new child to the population
  48. }
  49. }
  50.  
  51. /**
  52. * Calculates the fitness of a given string
  53. * @param String str
  54. */
  55. public int getFitness(String str)
  56. {
  57. int numCorrect=0;
  58. for (int i=0;i<str.length();i++) {
  59. if (str.charAt(i) == solution.charAt(i)) { // Check if the letter is correct
  60. numCorrect++; // Add it to the fitness score
  61. }
  62. }
  63. return numCorrect;
  64. }
  65.  
  66. /**
  67. * Mutates the given string
  68. * @param String str
  69. */
  70. public String mutate(String str)
  71. {
  72. StringBuilder builder = new StringBuilder(str); // Strings are immutable in Java, a StringBuilder must be used to change them
  73. 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
  74. return builder.toString(); // Return the created string
  75. }
  76.  
  77. /**
  78. * Gets the fittest from the last generation
  79. */
  80. public String getBest()
  81. {
  82. generations++; // incrememnts the number of generations
  83. String best = population.get(0); // sets the best to the first as default
  84. for(String x : population) // For each string in the populatio
  85. {
  86. if (getFitness(x) > getFitness(best)) { // Check if it is the fittest
  87. best = x; // Set it as the best
  88. }
  89. }
  90. System.out.println("Best of Generation "+generations+" : "+best); // Print who is the best
  91. population.clear(); // Reset the population ready for the next generation
  92. return best;
  93. }
  94.  
  95. /**
  96. * Simulates a new generation based on the strongest from the last
  97. */
  98. public void nextGeneration(String best)
  99. {
  100. for (int i=0;i < generationSize; i++) { // Iterate until we reach the assigned generation size
  101. String newString = mutate(best); // Mutate the best from before
  102. population.add(newString); // Add it to the population
  103. if (newString.equals(solution)){ // If it is the solution
  104. System.out.println("SOLUTION FOUND: "+newString); // Say so
  105. System.exit(0); // and quit
  106. }
  107.  
  108. }
  109. }
  110.  
  111. /**
  112. * Main function
  113. * Mainly handling command line arguments, you can ignore.
  114. */
  115. public static void main(String[] args)
  116. {
  117. try {
  118. int num = Integer.parseInt(args[1]);
  119. new Genetic(args[0], num);
  120. }
  121. catch(ArrayIndexOutOfBoundsException ex)
  122. {
  123. System.err.println("Please provide 2 arguments, the target string and the size of the generations to simulate.");
  124. System.exit(1);
  125. }
  126. catch (NumberFormatException e) {
  127. System.err.println("Second argument was not an integer.");
  128. System.exit(1);
  129. }
  130. }
  131. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement