import java.util.*; import java.io.*; /* Jedinci */ class Jedinec implements Comparable { private int[] geny; private double fitness; private Random rand; /* Konstruktor – vygeneruje náhodného binárního jedince */ public Jedinec(int d, Random rand) { this.rand = rand; geny = new int[d]; for (int i=0; i ruletovaSelekce(ArrayList gen, int n) { // Spočítej celkovou fitness double total = 0; for (int i=0; i vyber = new ArrayList(); for (int i=0; i generace = new ArrayList(); for (int i=0; i vyber = ruletovaSelekce(generace, N); // Křížení for (int i=0; i best.getFitness()) best = generace.get(0); } log.write(generace, IT); return best; } /* Zapíše do souboru fitness a geny nejlepšího jedince */ public static void zaloguj_nejlepsiho(Jedinec best) { try { FileWriter fw = new FileWriter("best.log"); fw.write("Fitness: " + best.getFitness() + "\n"); fw.write("Geny:\n"); for (int i=0; i best.getFitness()) { best = j; zaloguj_nejlepsiho(best); } } } } /* Třída pro logování výpočtů – není třeba jí rozumět */ class Logovani { FileWriter fw; /* Otevře soubor pro logování */ public void open(int b) { try { fw = new FileWriter("beh" + b + ".log"); } catch (IOException ioe) { System.err.println("IOException"); System.exit(1); } } /* Ukončí logování */ public void close() { try { fw.close(); } catch (IOException ioe) { System.err.println("IOException"); System.exit(1); } } /* Udělá zápis z generace gen z iterace it */ public void write(ArrayList gen, int it) { double maxi = 0.0; double total = 0.0; for (int i=0; i maxi) ? gen.get(i).getFitness() : maxi; } try { fw.write(it + "\t" + (total/gen.size()) +"\t" + maxi + "\n"); } catch (IOException ioe) { System.err.println("IOException"); System.exit(1); } } }