Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | None | 0 0
  1. package br.edu.ifce.maracanau.ia.algoritmoGenetico;
  2.  
  3. import br.edu.ifce.maracanau.ia.algoritmoGenetico.Tabuleiro;
  4.  
  5. import org.jgap.Chromosome;
  6. import org.jgap.Configuration;
  7. import org.jgap.FitnessFunction;
  8. import org.jgap.Gene;
  9. import org.jgap.Genotype;
  10. import org.jgap.IChromosome;
  11. import org.jgap.InvalidConfigurationException;
  12. import org.jgap.impl.DefaultConfiguration;
  13. import org.jgap.impl.IntegerGene;
  14.  
  15. public class Genetico {
  16.  
  17.     private static final double VALOR_ESPERADO = 28;
  18.     private static final int N_RAINHA = 8;
  19.     private static final int POPULACAO = 300;
  20.     private static final int EPOCA = 600;
  21.  
  22.     public static Tabuleiro resolve() throws InvalidConfigurationException {
  23.         Tabuleiro tabuleiro = new Tabuleiro();
  24.  
  25.         // Inicia com a configuração padrão
  26.         // -------------------------------------------------------------
  27.         Configuration conf = new DefaultConfiguration();
  28.         conf.setPreservFittestIndividual(true);        
  29.         FitnessFunction minhaFuncao = new Fitness();
  30.         conf.setFitnessFunction(minhaFuncao);
  31.  
  32.         Gene[] sampleGene = new Gene[N_RAINHA];
  33.         for (int i = 0; i < sampleGene.length; i++) {
  34.             sampleGene[i] = new IntegerGene(conf, 0, (N_RAINHA - 1));
  35.         }
  36.         IChromosome sampleChromosome = new Chromosome(conf, sampleGene);
  37.         conf.setSampleChromosome(sampleChromosome);
  38.  
  39.         conf.setPopulationSize(POPULACAO);
  40.  
  41.         Genotype population = Genotype.randomInitialGenotype(conf);
  42.  
  43.         boolean rodaAlgotimo = true;
  44.  
  45.         int cont = 0;
  46.         while (rodaAlgotimo && cont <= EPOCA) {
  47.             population.evolve();
  48.             IChromosome bestSolutionSoFar = population.getFittestChromosome();
  49.             System.out.println(bestSolutionSoFar);
  50.  
  51.             if (bestSolutionSoFar.getFitnessValue() == VALOR_ESPERADO) {
  52.                 break;
  53.             }
  54.             cont++;
  55.         }
  56.  
  57.         //monta a matriz
  58.         int linha;
  59.         int coluna = 0;
  60.         int[][] estado = new int[N_RAINHA][N_RAINHA];
  61.         for (Gene gene : population.getFittestChromosome().getGenes()) {
  62.  
  63.             linha = (Integer) gene.getAllele();
  64.             estado[linha][coluna] = 1;
  65.             coluna++;
  66.         }
  67.  
  68.         tabuleiro.setEstado(estado);
  69.  
  70.         return tabuleiro;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement