-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.cpp
More file actions
489 lines (366 loc) · 11.8 KB
/
Copy pathcode.cpp
File metadata and controls
489 lines (366 loc) · 11.8 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//-----------------------------------------ga_tutorial.cpp--------------------------------------
//
// code to illustrate the use of a genetic algorithm to solve the problem described
// at www.ai-junkie.com
//
// by Mat Buckland aka fup
//
//-----------------------------------------------------------------------------------------------
#include <string>
#include <stdlib.h>
#include <iostream.h>
#include <time.h>
#include <math.h>
using std::string;
#define CROSSOVER_RATE 0.7
#define MUTATION_RATE 0.001
#define POP_SIZE 100 //must be an even number
#define CHROMO_LENGTH 300
#define GENE_LENGTH 4
#define MAX_ALLOWABLE_GENERATIONS 400
//returns a float between 0 & 1
#define RANDOM_NUM ((float)rand()/(RAND_MAX+1))
//----------------------------------------------------------------------------------------
//
// define a data structure which will define a chromosome
//
//----------------------------------------------------------------------------------------
struct chromo_typ
{
//the binary bit string is held in a std::string
string bits;
float fitness;
chromo_typ(): bits(""), fitness(0.0f){};
chromo_typ(string bts, float ftns): bits(bts), fitness(ftns){}
};
/////////////////////////////////prototypes/////////////////////////////////////////////////////
void PrintGeneSymbol(int val);
string GetRandomBits(int length);
int BinToDec(string bits);
float AssignFitness(string bits, int target_value);
void PrintChromo(string bits);
void PrintGeneSymbol(int val);
int ParseBits(string bits, int* buffer);
string Roulette(int total_fitness, chromo_typ* Population);
void Mutate(string &bits);
void Crossover(string &offspring1, string &offspring2);
//-------------------------------main--------------------------------------------------
//
//-------------------------------------------------------------------------------------
int main()
{
//seed the random number generator
srand((int)time(NULL));
//just loop endlessly until user gets bored :0)
while (true)
{
//storage for our population of chromosomes.
chromo_typ Population[POP_SIZE];
//get a target number from the user. (no error checking)
float Target;
cout << "\nInput a target number: ";
cin >> Target;
cout << endl << endl;
//first create a random population, all with zero fitness.
for (int i=0; i<POP_SIZE; i++)
{
Population[i].bits = GetRandomBits(CHROMO_LENGTH);
Population[i].fitness = 0.0f;
}
int GenerationsRequiredToFindASolution = 0;
//we will set this flag if a solution has been found
bool bFound = false;
//enter the main GA loop
while(!bFound)
{
//this is used during roulette wheel sampling
float TotalFitness = 0.0f;
// test and update the fitness of every chromosome in the
// population
for (int i=0; i<POP_SIZE; i++)
{
Population[i].fitness = AssignFitness(Population[i].bits, Target);
TotalFitness += Population[i].fitness;
}
// check to see if we have found any solutions (fitness will be 999)
for (i=0; i<POP_SIZE; i++)
{
if (Population[i].fitness == 999.0f)
{
cout << "\nSolution found in " << GenerationsRequiredToFindASolution << " generations!" << endl << endl;;
PrintChromo(Population[i].bits);
bFound = true;
break;
}
}
// create a new population by selecting two parents at a time and creating offspring
// by applying crossover and mutation. Do this until the desired number of offspring
// have been created.
//define some temporary storage for the new population we are about to create
chromo_typ temp[POP_SIZE];
int cPop = 0;
//loop until we have created POP_SIZE new chromosomes
while (cPop < POP_SIZE)
{
// we are going to create the new population by grabbing members of the old population
// two at a time via roulette wheel selection.
string offspring1 = Roulette(TotalFitness, Population);
string offspring2 = Roulette(TotalFitness, Population);
//add crossover dependent on the crossover rate
Crossover(offspring1, offspring2);
//now mutate dependent on the mutation rate
Mutate(offspring1);
Mutate(offspring2);
//add these offspring to the new population. (assigning zero as their
//fitness scores)
temp[cPop++] = chromo_typ(offspring1, 0.0f);
temp[cPop++] = chromo_typ(offspring2, 0.0f);
}//end loop
//copy temp population into main population array
for (i=0; i<POP_SIZE; i++)
{
Population[i] = temp[i];
}
++GenerationsRequiredToFindASolution;
// exit app if no solution found within the maximum allowable number
// of generations
if (GenerationsRequiredToFindASolution > MAX_ALLOWABLE_GENERATIONS)
{
cout << "No solutions found this run!";
bFound = true;
}
}
cout << "\n\n\n";
}//end while
return 0;
}
//---------------------------------GetRandomBits-----------------------------------------
//
// This function returns a string of random 1s and 0s of the desired length.
//
//-----------------------------------------------------------------------------------------
string GetRandomBits(int length)
{
string bits;
for (int i=0; i<length; i++)
{
if (RANDOM_NUM > 0.5f)
bits += "1";
else
bits += "0";
}
return bits;
}
//---------------------------------BinToDec-----------------------------------------
//
// converts a binary string into a decimal integer
//
//-----------------------------------------------------------------------------------
int BinToDec(string bits)
{
int val = 0;
int value_to_add = 1;
for (int i = bits.length(); i > 0; i--)
{
if (bits.at(i-1) == '1')
val += value_to_add;
value_to_add *= 2;
}//next bit
return val;
}
//---------------------------------ParseBits------------------------------------------
//
// Given a chromosome this function will step through the genes one at a time and insert
// the decimal values of each gene (which follow the operator -> number -> operator rule)
// into a buffer. Returns the number of elements in the buffer.
//------------------------------------------------------------------------------------
int ParseBits(string bits, int* buffer)
{
//counter for buffer position
int cBuff = 0;
// step through bits a gene at a time until end and store decimal values
// of valid operators and numbers. Don't forget we are looking for operator -
// number - operator - number and so on... We ignore the unused genes 1111
// and 1110
//flag to determine if we are looking for an operator or a number
bool bOperator = true;
//storage for decimal value of currently tested gene
int this_gene = 0;
for (int i=0; i<CHROMO_LENGTH; i+=GENE_LENGTH)
{
//convert the current gene to decimal
this_gene = BinToDec(bits.substr(i, GENE_LENGTH));
//find a gene which represents an operator
if (bOperator)
{
if ( (this_gene < 10) || (this_gene > 13) )
continue;
else
{
bOperator = false;
buffer[cBuff++] = this_gene;
continue;
}
}
//find a gene which represents a number
else
{
if (this_gene > 9)
continue;
else
{
bOperator = true;
buffer[cBuff++] = this_gene;
continue;
}
}
}//next gene
// now we have to run through buffer to see if a possible divide by zero
// is included and delete it. (ie a '/' followed by a '0'). We take an easy
// way out here and just change the '/' to a '+'. This will not effect the
// evolution of the solution
for (i=0; i<cBuff; i++)
{
if ( (buffer[i] == 13) && (buffer[i+1] == 0) )
buffer[i] = 10;
}
return cBuff;
}
//---------------------------------AssignFitness--------------------------------------
//
// given a string of bits and a target value this function will calculate its
// representation and return a fitness score accordingly
//------------------------------------------------------------------------------------
float AssignFitness(string bits, int target_value)
{
//holds decimal values of gene sequence
int buffer[(int)(CHROMO_LENGTH / GENE_LENGTH)];
int num_elements = ParseBits(bits, buffer);
// ok, we have a buffer filled with valid values of: operator - number - operator - number..
// now we calculate what this represents.
float result = 0.0f;
for (int i=0; i < num_elements-1; i+=2)
{
switch (buffer[i])
{
case 10:
result += buffer[i+1];
break;
case 11:
result -= buffer[i+1];
break;
case 12:
result *= buffer[i+1];
break;
case 13:
result /= buffer[i+1];
break;
}//end switch
}
// Now we calculate the fitness. First check to see if a solution has been found
// and assign an arbitarily high fitness score if this is so.
if (result == (float)target_value)
return 999.0f;
else
return 1/(float)fabs((double)(target_value - result));
// return result;
}
//---------------------------------PrintChromo---------------------------------------
//
// decodes and prints a chromo to screen
//-----------------------------------------------------------------------------------
void PrintChromo(string bits)
{
//holds decimal values of gene sequence
int buffer[(int)(CHROMO_LENGTH / GENE_LENGTH)];
//parse the bit string
int num_elements = ParseBits(bits, buffer);
for (int i=0; i<num_elements; i++)
{
PrintGeneSymbol(buffer[i]);
}
return;
}
//--------------------------------------PrintGeneSymbol-----------------------------
//
// given an integer this function outputs its symbol to the screen
//----------------------------------------------------------------------------------
void PrintGeneSymbol(int val)
{
if (val < 10 )
cout << val << " ";
else
{
switch (val)
{
case 10:
cout << "+";
break;
case 11:
cout << "-";
break;
case 12:
cout << "*";
break;
case 13:
cout << "/";
break;
}//end switch
cout << " ";
}
return;
}
//------------------------------------Mutate---------------------------------------
//
// Mutates a chromosome's bits dependent on the MUTATION_RATE
//-------------------------------------------------------------------------------------
void Mutate(string &bits)
{
for (int i=0; i<bits.length(); i++)
{
if (RANDOM_NUM < MUTATION_RATE)
{
if (bits.at(i) == '1')
bits.at(i) = '0';
else
bits.at(i) = '1';
}
}
return;
}
//---------------------------------- Crossover ---------------------------------------
//
// Dependent on the CROSSOVER_RATE this function selects a random point along the
// lenghth of the chromosomes and swaps all the bits after that point.
//------------------------------------------------------------------------------------
void Crossover(string &offspring1, string &offspring2)
{
//dependent on the crossover rate
if (RANDOM_NUM < CROSSOVER_RATE)
{
//create a random crossover point
int crossover = (int) (RANDOM_NUM * CHROMO_LENGTH);
string t1 = offspring1.substr(0, crossover) + offspring2.substr(crossover, CHROMO_LENGTH);
string t2 = offspring2.substr(0, crossover) + offspring1.substr(crossover, CHROMO_LENGTH);
offspring1 = t1; offspring2 = t2;
}
}
//--------------------------------Roulette-------------------------------------------
//
// selects a chromosome from the population via roulette wheel selection
//------------------------------------------------------------------------------------
string Roulette(int total_fitness, chromo_typ* Population)
{
//generate a random number between 0 & total fitness count
float Slice = (float)(RANDOM_NUM * total_fitness);
//go through the chromosones adding up the fitness so far
float FitnessSoFar = 0.0f;
for (int i=0; i<POP_SIZE; i++)
{
FitnessSoFar += Population[i].fitness;
//if the fitness so far > random number return the chromo at this point
if (FitnessSoFar >= Slice)
return Population[i].bits;
}
return "";
}