private void completeGrid(IIndividual individual, SudokuGrid grid) { List<IGene> genes = individual.getGenes(); List<Integer> indexes = new ArrayList<>(); for (IGene gene : genes) { indexes.add(gene.getValue()); } grid.completeGrid(indexes); }
private boolean updateFitnesses(Collection<IIndividual> individuals, IStatistic stats) { List<Integer> numBlanksList = new ArrayList<>(); for (IIndividual individual : individuals) { SudokuGrid grid = new SudokuGrid(_grid); completeGrid(individual, grid); int numBlanks = grid.getNumBlanks(); numBlanksList.add(numBlanks); stats.update(numBlanks); if (numBlanks == 0) { // solution found System.out.printf("Solution:%n%s%n%n", grid.toPrettyString()); return false; } } System.out.printf("blanksStats: %s%n", stats); int i = 0; for (IIndividual individual : individuals) { int numBlanks = numBlanksList.get(i++); double fitness = Math.pow(numBlanks, -8); individual.setFitness(fitness); } return true; }
public static void main(String[] args) { IRandom random = new RandomWrapper(); SudokuGrid grid = new SudokuGrid( // 6, 0, 0, 0, 0, 0, 0, 4, 0, // 0, 0, 5, 0, 0, 2, 0, 0, 7, // 7, 2, 9, 0, 0, 0, 0, 0, 3, // 0, 9, 0, 0, 4, 0, 0, 0, 1, // 0, 0, 0, 0, 6, 0, 0, 0, 0, // 4, 0, 0, 0, 8, 0, 0, 7, 0, // 3, 0, 0, 0, 0, 0, 1, 6, 5, // 2, 0, 0, 4, 0, 0, 8, 0, 0, // 0, 5, 0, 0, 0, 0, 0, 0, 4 // ); IIndividualFactory individualFactory = IndividualFactories.getIndividualFactory( 100, grid.getNumBlanks(), grid.getSizeSquared(), random); Collection<IIndividual> individuals = individualFactory.getIndividuals(); IIndividualEvolver evolver = IndividualEvolvers.getEvolver(random, 0.01); SudokuSolver solver = new SudokuSolver(grid); long start = System.currentTimeMillis(); for (int generation = 0; generation < 50; generation++) { IStatistic stats = new Statistic(); if (!solver.updateFitnesses(individuals, stats)) { long duration = System.currentTimeMillis() - start; System.out.printf("Took %d milliconds and %d generations %n", duration, generation); break; } individuals = evolver.getNextGeneration(individuals); System.out.println(String.format("%d, individuals=%s%n", generation, individuals.toString())); } }