[C con Clase] AYUDA URGENTE PORFAVOR

mario Guzman Moreno mguzman_18 en hotmail.com
Sab Mar 13 20:36:17 CET 2010


hola a todos, estado tratando de entender el sgt codigo pero aun me queda una dudad en estas 3 funciones siguientes, me podrian explicar como funcionan por favor:
void elitism(ga_vector &population, ga_vector &buffer, int esize )
void mutate(ga_struct &member)
void mate(ga_vector &population, ga_vector &buffer)
 y xq solo corre en el DEV C++ y no en el TURBO C++; el codigo es el sgt: mis dudas lo dejo resaltado con negrita
gracias de antemano.

#pragma warning(disable:4786)        // disable debug warning  DESACTIVAR LA ALERTA DE DEPURACION
#include <iostream>                    // for cout etc.
#include <vector>                    // for vector class
#include <string>                    // for string class
#include <algorithm>                // for sort algorithm PARA ALGORITMO DE ORDENACION
#include <time.h>                    // for random seed
#include <math.h>                    // for abs()
#include <stdio.h>
#include <conio.h>                   //getch()

#define GA_POPSIZE        2048        // ga population size  TAMAÑO DE LA POBLACION
#define GA_MAXITER        16384        // maximum iterations  MAXIMO DE ITERACIONES
#define GA_ELITRATE        0.10f        // elitism rate    TASA DE ELITISMO
#define GA_MUTATIONRATE    0.25f        // mutation rate   LA TASA DE MUTACION
#define GA_MUTATION        RAND_MAX * GA_MUTATIONRATE
#define GA_TARGET        std::string("Hola Mundo!")

using namespace std;                // polluting global namespace, but hey...
int i=0;
struct ga_struct           //estructura del AG
{
    string str;                        // the string      LA CADENA
    unsigned int fitness;            // its fitness    SU APTITUD
};

typedef vector<ga_struct> ga_vector;// for brevity  PARA ABREVIAR ????????????

void init_population(ga_vector &population,
                     ga_vector &buffer )
{
    int tsize = GA_TARGET.size();  //tsize toma el tamaño de la cadena inicial

    for (int i=0; i<GA_POPSIZE; i++) {  // generará un maximo de 2048 vueltas
        ga_struct citizen;    // crea la variable citizen de tipo ga_struct
        
        citizen.fitness = 0;
        citizen.str.erase(); //creo q elimina el contenido de la cadena, inicializandolo

        for (int j=0; j<tsize; j++)
            citizen.str += (rand() % 90) + 32;     

           //aqui se va llenando la poblacion incertando los elementos en el vector population
        population.push_back(citizen);  //ver este enlace http://ilengine.wikidot.com/vector
    }    

    buffer.resize(GA_POPSIZE); // genera el vector buffer con con la cantidad de GA_POPSIZE(2048) elementos
}

void calc_fitness(ga_vector &population)
{
    string target = GA_TARGET; // target recibe la cadena a evolucionar
    int tsize = target.size();   // tsize obtiene el tamaño de la cadena
    unsigned int fitness;

    for (int i=0; i<GA_POPSIZE; i++) {   //va a dar 2048 vueltas
        fitness = 0;
        for (int j=0; j<tsize; j++) {   // esto se hace por cada individuo (cada frase)
            fitness += abs(int(population[i].str[j] - target[j]));
        }
          //el valor acumulado total se almacena en cada una de los individuos (cada frase)
        population[i].fitness = fitness;
    }
}
 //retorna verdadero o falso dependiendo de la condicion
bool fitness_sort(ga_struct x, ga_struct y) 
{ return (x.fitness < y.fitness); }


inline void sort_by_fitness(ga_vector &population) //??????????????????
{ sort(population.begin(), population.end(), fitness_sort); }

void elitism(ga_vector &population, 
                ga_vector &buffer, int esize )
{
    for (int i=0; i<esize; i++) {
        buffer[i].str = population[i].str;
        buffer[i].fitness = population[i].fitness;
    }
}

void mutate(ga_struct &member)
{
    int tsize = GA_TARGET.size();
    int ipos = rand() % tsize;
    int delta = (rand() % 90) + 32;

    member.str[ipos] = ((member.str[ipos] + delta) % 122);
}

void mate(ga_vector &population, ga_vector &buffer)
{
    int esize = GA_POPSIZE * GA_ELITRATE;
    int tsize = GA_TARGET.size(), spos, i1, i2;

    elitism(population, buffer, esize);

    // Mate the rest         MATA EL RESTO
    for (int i=esize; i<GA_POPSIZE; i++) {
        i1 = rand() % (GA_POPSIZE / 2);
        i2 = rand() % (GA_POPSIZE / 2);
        spos = rand() % tsize;

        buffer[i].str = population[i1].str.substr(0, spos) + 
                        population[i2].str.substr(spos, esize - spos);

        if (rand() < GA_MUTATION) mutate(buffer[i]);
    }
}
 // imprime el mejor osea el primer individuo de la poblacion
inline void print_best(ga_vector &gav)

{
 i++;
 cout << i;
 cout << " Best: " << gav[0].str << " (" << gav[0].fitness << ")" << endl;
 }

// esta funcion es para realizar el intercambio entre dos variables
inline void swap(ga_vector *&population,
                 ga_vector *&buffer)
     {
       ga_vector *temp = population; population = buffer; buffer = temp;
     }

int main()
{
    srand(unsigned(time(NULL)));//?????????  ???????????????????????????

    ga_vector pop_alpha, pop_beta;   //creo dos variables vectores
    ga_vector *population, *buffer;  //creo dos punteros de vestores

    init_population(pop_alpha, pop_beta);
    population = &pop_alpha;
    buffer = &pop_beta;

    for (int i=0; i<GA_MAXITER; i++) {
        calc_fitness(*population);        // CÁLCULO DE LA APTITUD
        sort_by_fitness(*population);    // ORDENARLOS
        print_best(*population);        // print the best one  INPRIME EL MEJOR

        if ((*population)[0].fitness == 0) break;

        mate(*population, *buffer);        // mate the population together
        swap(population, buffer);        // swap buffers  BUFFERS DE INTERCAMBIO
    }
 getch();

    return 0;
}

 


 		 	   		  
_________________________________________________________________
¿Quieres saber qué PC eres? ¡Descúbrelo aquí!
http://www.quepceres.com/
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: <http://listas.conclase.net/pipermail/cconclase_listas.conclase.net/attachments/20100313/ce3af55b/attachment.html>


Más información sobre la lista de distribución Cconclase