Dev - C++ - Necesito un algoritmo genetico en C++

 
Vista:

Necesito un algoritmo genetico en C++

Publicado por Brenda (1 intervención) el 25/10/2004 05:15:33
por favor me urge un programa de algoritmos geneticos en C++...si alguien tiene uno por favor pasemelo...lo necesito...bueno se los agradezco...
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:Necesito un algoritmo genetico en C++

Publicado por Ismael (1 intervención) el 26/10/2004 20:04:01
Mira en:
http://c.conclase.net/fuentes.php?tema=6#item2

http://www.elrincondelprogramador.com/default.asp?pag=articulos/leer.asp&id=6

Un saludo
Ismael
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Necesito un algoritmo genetico en C

Publicado por Percy Canorio (1 intervención) el 09/12/2011 18:45:13
/algoritmo genetico en C++ optimizar F(x)
//clase desarrollado el 24nov
//definicion de librerias
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <conio.h>
#include <iostream>

//definicion de constantes
#define TAMANO_POB 13
#define LONG_CROM 343
#define PCRUCE 0.34
#define PMUTACION 0.33

//definicion de la estructura poblacion
struct poblacion{
double cantidad;
unsigned int cromosoma[LONG_CROM];
double capacidad;
double frec;
double frec_ac;
};

//declaracion de variables de tipo poblacion
struct poblacion pob[TAMANO_POB],best,bestgen;
struct poblacion nueva_pob[TAMANO_POB];

//declaracion de funciones a emplear en el codigo genetico
void initialize_poblacion();
double funcion(double cantidad);
double valor(int indiv,int pos_ini,int pos_fin,int lim_inf,int lim_sup);
void evaluar();
void mejor();
float aleatorio();
int alea_int(int lim_inf,int lim_sup);
void seleccion();
void cruce();
void crossover(int parent1,int parent2);
void mutacion();
void mutation(int pos);

//definicion de funcion principal
void main(){
int t;
double cap_ant;

t=0;
initialize_poblacion();
evaluar();
printf("%4s %7s %6s\n",
"generacion","bg can", "bg cap");
printf(
"%4d %7.0f %7.1f \n",
t,best.cantidad,best.capacidad);
cap_ant=best.capacidad;
while(t<1000){
t++;
seleccion();
cruce();
mutacion();
evaluar();
if(best.capacidad!=cap_ant){
printf( "%4d %7.0f %7.1f \n", t,best.cantidad,best.capacidad);
cap_ant=best.capacidad;
}
}
getch();
}

//inicializar de manera aleatoria la poblacion OK
void initialize_poblacion(){
int i,j;
srand( (unsigned)time( NULL ) );
for(i=0;i<TAMANO_POB;i++)
for(j=0;j<LONG_CROM;j++)
pob[i].cromosoma[j]=alea_int(0,1);
}

//funcion que genera un numero aleatorio de tipo flotante
float aleatorio(){
return (float) (rand()*10001/
(RAND_MAX-1))/10000;
}

// funcion que devuelve de manera aleatoria el valor de un gen
int alea_int(int lim_inf,int lim_sup){
return (int) (aleatorio()*
(lim_sup-lim_inf+1))+lim_inf;
}


//funcion que calcula F(x), F(x)/sum, F.acum
void evaluar(){
int i;
double suma=0;

for(i=0;i<TAMANO_POB;i++){
pob[i].cantidad=valor(i,0,5,-1,3);
pob[i].capacidad=funcion(pob[i].cantidad);
suma+=pob[i].capacidad;
}
pob[0].frec=pob[0].capacidad/suma;
pob[0].frec_ac=pob[0].frec;
for(i=1;i<TAMANO_POB;i++){
pob[i].frec=pob[i].capacidad/suma;
pob[i].frec_ac=pob[i-1].frec_ac +
pob[i].frec;
}
mejor();
}

//calcular el valor de la funcion a optimizar
double funcion(double cantidad){
double fx;
fx= 10+sin(10*3.14159*cantidad);
return fx;
}

//calcula el valor real X de un cromosoma
double valor(int indiv,int pos_ini,int pos_fin,
int lim_inf,int lim_sup){

double factor,val;
int i;

factor=1;
val=0;
for(i=pos_fin;i>=pos_ini;i--){
val+=
(pob[indiv].cromosoma[i] * factor);
factor*=2;
}
val=lim_inf + (lim_sup-lim_inf) /(pow((double)2,pos_fin-pos_ini+1)-1) * val;
return val;
}

//guarda los mejores cromosomas
void mejor(){
int i;

i=0;
best=pob[i];
for(i=1;i<TAMANO_POB;i++)
if(best.capacidad<pob[i].capacidad)
best=pob[i];
if(bestgen.capacidad<best.capacidad)
bestgen=best;

}

//selecciona los mejores cromosomas
void seleccion(){
float aleat;
int i,j;

for(i=0;i<TAMANO_POB;i++){
aleat=aleatorio();
j=0;
while(aleat>pob[j].frec_ac &&
j<TAMANO_POB-1) j++;
nueva_pob[i]=pob[j];
}
for(i=0;i<TAMANO_POB;i++)
pob[i]=nueva_pob[i];
}
//identifica el punto de cruce
void cruce(){
int selec[TAMANO_POB],indice,i;
float aleat;

indice=-1;
for(i=0;i<TAMANO_POB;i++){
aleat=aleatorio();
if(aleat<PCRUCE){
indice++;
selec[indice]=i;
}
}
if(indice % 2) indice--;
for(i=0;i<indice/2;i++)
crossover(selec[i],selec[indice/2+i]);
}

//cruza los cromosomas
void crossover(int padre1,int padre2){
int punto_cruce,i;
unsigned int temp;

punto_cruce=alea_int(0,LONG_CROM-2);
for(i=punto_cruce+1;i<LONG_CROM;i++){
temp=pob[padre1].cromosoma[i];
pob[padre1].cromosoma[i]=
pob[padre2].cromosoma[i];
pob[padre2].cromosoma[i]=temp;
}
}

//compara las probabilidades de los genes con PMUTACION
void mutacion(){
int selec[TAMANO_POB],indice,i;
float aleat;

indice=-1;
for(i=0;i<TAMANO_POB;i++){
aleat=aleatorio();
if(aleat<PMUTACION){
indice++;
selec[indice]=i;
}
}
for(i=0;i<indice;i++) mutation(selec[i]);
}

//funcion que va mutar
void mutation(int pos){
int punto;

punto=alea_int(0,LONG_CROM-1);
pob[pos].cromosoma[punto]=
!pob[pos].cromosoma[punto];
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Necesito un algoritmo genetico en C

Publicado por Esteban Vargas (1 intervención) el 17/06/2015 06:57:02
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
string padre1[10];
string padre2[10];
string genes[10];
string hijo1[10];
string hijo2[10];
string rutas[10][10];
 
struct Vertices{
    char nombre[15];
    int rutaHabilitada;         /// 1-Si // 0-No
    int visitado;               /// 1-Si // 0-No
    struct Vertices *sigV;
    struct Arco *sigA;
    Vertices(const char *nomC,int rutHab){
        strcpy(nombre,nomC);
        rutaHabilitada = rutHab;
        visitado = 0;
        sigV = NULL;
        sigA = NULL;
    }
}*primeroVertices;
 
struct Arco{  ///          Cada Arco Representará las Autopistas o Caminos entre las Ciudades
    char tipoTransporte[15];
    int costo;
    int duracion;
    int distancia;
    int estadoRuta;             /// 1- Activo // 0 -Inactivo
    struct Vertices *sigV;  /// Destino
    struct Arco *sigA;
    Arco(const char *transp, int cost,int dur,int dist,int estado){
        strcpy(tipoTransporte,transp);
        costo = cost;
        duracion = dur;
        distancia = dist;
        estadoRuta = estado;
        sigV = NULL;
    }
};
 
struct Pila{ /// Para utilizado para diferentes consultas, ruta mas corta, tamaño de la ruta, velocidad maxima,etc
    string ciudad;
    struct Pila * sig;
    struct Arco *sigA;
    Pila(string c){
        ciudad=c;
        sigA = NULL;
        sig = NULL;
    }
 
}*pila,*pilaMin;
 
void mutarGen(){
    srand(time(NULL));
    int genRandom=rand()%g;
    cout<<"Padre sin mutacion: ";
    for(int i =0;i<10;i++){
        if(padre1[i]=="")
            break;
        cout<<padre1[i];
    }
    cout<<endl;
    if (padre1[2]!="")
        padre1[2]= genes[genRandom];
    else
        padre1[1]= genes[genRandom];
 
    cout<<"Padre mutado: ";
    for(int i =0;i<10;i++){
        if(padre1[i]=="")
            break;
        cout<<padre1[i];
    }
    cout<<endl;
}
 
void seleccionarPadres(int factor){
    int numeroPadres = 1;
    for(int i=0;i<10;i++){
        if((tCostos[i] <= factor) and (tCostos[i] != 0)){
            if (numeroPadres==1){
                for(int j=0;j<10;j++){
                    padre1[j] = rutas[i][j];
                }
            }
            else{
                for(int j=0;j<10;j++){
                    padre2[j] = rutas[i][j];
                }
            }
            numeroPadres++;
        }
        if((numeroPadres>2) or (rutas[i][0]==""))
            break;
    }
 
    if (numeroPadres>2){
        hacerCruce();
    }
    else
        mutarGen();
}
 
void hacerCruce(){
    for(int i=0;i<10;i++){
        if (i<=1){
            hijo1[i] = padre1[i];
            hijo2[i] = padre2[i];
        }
        else{
            hijo1[i] = padre2[i];
            hijo2[i] = padre1[i];
        }
    }
    cout<<"Padre 1: ";
    for(int k=0;k<10;k++){
        if (padre1[k] == "")
            break;
        cout<<padre1[k];
    }
    cout<<endl;
    cout<<"Padre 2: ";
    for(int k=0;k<10;k++){
        if (padre2[k] == "")
            break;
        cout<<padre2[k];
    }
    cout<<endl;
 
    cout<<"Hijo 1: ";
    for(int k=0;k<10;k++){
        if (hijo1[k] == "")
            break;
        cout<<hijo1[k];
    }
    cout<<endl;
 
    cout<<"Hijo 2: ";
    for(int k=0;k<10;k++){
        if (hijo2[k] == "")
            break;
        cout<<hijo2[k];
    }
}
 
void extraerPadres(struct Pila *pila){
    if(pila == NULL)
        return;
    extraerPadres(pila->sig);
    //cout<<pila->ciudad<<", ";
 
    rutas[u][w] = pila->ciudad;
    w++;
}
void sumarRutasCosto(){
    int i=0;
    int j=0;
    x = 0;
    int suma = 0;
    while (i<10){
        struct Vertices * tempVertice = buscarVertice(rutas[i][j]);
        if (tempVertice!=NULL){
            struct Arco * tempArco=buscarArco(tempVertice,rutas[i][j+1]);
            if (tempArco!=NULL){
                suma = suma + tempArco->costo;
            }
 
        }
        if(j==8){
            tCostos[x] = suma;
            suma = 0;
            i++;
            x++;
            j=-1;
        }
        j++;
    }
}
 
void ruta(struct Vertices * origen, string destino){
    if(origen == NULL)
        return;
 
    if(origen->visitado == true){
        //totalCosto = 0;
        return;
    }
 
    push(origen->nombre);
    if(origen->nombre == destino){
        ///cout<<"Si existe ruta.."<<endl;
        hayRuta = true;
        ///tCostos[x] = totalCosto;
        extraerPadres(pila);
        ///totalCosto = 0;
        conta++;
        u++;
        w=0;
        ///x++;
        cout<<endl;
        return;
    }
 
    else{
        origen->visitado = true;  /// Lo voy a visitar
 
        struct Arco * tempArco = origen->sigA;
        while(tempArco!=NULL){
            if (tempArco->estadoRuta!=0){
                ruta(buscarVertice(tempArco->sigV->nombre),destino);
            }
           /// totalCosto = totalCosto + tempArco->costo;
            tempArco = tempArco->sigA;
            pop(); /// Se coloca aqui porque ya aqui esta en un nuevo camino o ruta
        }
        origen->visitado = false;
    }
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Necesito un algoritmo genetico en visual c++

Publicado por guliver (1 intervención) el 17/11/2017 23:05:39
amigo como puedo levantar este ejercicio en visual c++ porfavor
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar