void AlGenetico::generar(Bola* pPoblacionInicial){
	int posBB[dos]={genRand(cero,posXPista),genRand(cero,posYPista)};
	for(int i=cero; i<poblacionI;i++){
		unsigned short direcc=(unsigned short)genRand(uno,anguloMax);
		unsigned short fuerza=(unsigned short)genRand(cero,fuerzaMax);
		int pos[dos]={genRand(cero,posXPista),genRand(cero,posYPista)};
		pPoblacionInicial= new Bola(posBB);
		pPoblacionInicial->setAttr(direcc,fuerza,pos);
		pPoblacionInicial++;
	}
	pPoblacionInicial-=10;
	/**
	 * for para encliclar hasta alcazar objetivo o maximas generaciones
	 */
	for (int i=cero; i<CantGeneraciones; i++){
		for(int i=cero; i<poblacionI;i++){
			pPoblacionInicial->correr();
			_poblacion[i]=pPoblacionInicial;
			pPoblacionInicial++;
		}
		//condicion para detener el generico por objetivo alcanzado
		if(find())
			break;
		//si no, hacemos una nueva especie y volvemos a iterar
		reproducir();
	}
}
Exemple #2
0
double geneticAlgorithm(double bestA[10]){
  srand(time(NULL));
  double poblacion [1000][10];
  double poblacionN [1000][10];
  double parents[2][10];
  double hijo [10];
  double bestsofarP[10];
  double resultN[10];
  double bestsofar = -999;
  double prevresult = -999;
  double temp;
  int repetidos = 0;
  int j = 0;
  int i = 0;
  for(i = 0; i < 1000; i++) {
    for(j = 0; j < 10; j++) {
      poblacion[i][j] = (rand()%10 < 5 ? -1 : 1)*(double)rand() / ((double)(RAND_MAX)+(double)(1));
    }
  }
  int k,n = 0;
  double result = -999;
  while(result  < 9 && numeval <= NUMEVAL){
      prevresult = result;
      for(i = 0; i < 1000; i++){
	getParents(poblacion,parents);	
	reproducir(parents[0],parents[1],hijo);
	if(rand()%10 < 1){
	  mutar(hijo);
	}
	temp = evaluar(hijo);
	numeval++;
	if(temp > result){
	  result = temp;
	  memcpy(&resultN, &hijo, sizeof(double)*10);
	}
	memcpy(&poblacionN[i], &hijo,sizeof(double)*10);
      }
      memcpy(&poblacion,&poblacionN,sizeof(double)*10000);
      if(result > bestsofar) {
	repetidos = 0;
	bestsofar = result; 
	memcpy(bestsofarP, resultN,sizeof(double)*10);
      }else if(result == prevresult) {
	if(repetidos == 5){
	  result = bestsofar;
	  break;
	}
	repetidos++;
      }else if(result != prevresult) {
	repetidos = 0;
      }
      printf("BestSoFar: %lf Prev: %lf, Result: %lf \n",bestsofar,prevresult,result);
    }
  memcpy(bestA,bestsofarP,sizeof(double)*10);
  return result;
}