Genetic Algorithm

Hello I'm writing a genetic algorithm code to create a string. I run the code and it gets pretty close to my target, but then says the fitness is 1 when it is obviously not. Please help!

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
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <array>
#include <cstring>

using namespace std;

const int MAX_LOOP = 2000;  // max count of iterations
const int MAX_POOL = 2000;  // max size of matingpool[]
const int POP_COUNT = 200;  // max count of organisms in the pool

/* ASCII-values of SPACE, A-Z, a-z.
 */
const char alphanum[53] =
{   32, 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, 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
};
 
/* Creates strings of length 'length', filled with randomly choosen
 * alpanumeric characters.
 */
void
buildPopulation (string population[], int length)
{

    int z;
    int i;
    int a;
    string organism = "";

    i = 0;
    z = 1;
    while (z <= POP_COUNT)
    {
        organism = "";
        for (int a = 1; a <= length; a++)
        {
            organism = organism + alphanum[rand () % 52];
        }
        population[i] = organism;
        i++;
        z++;
    }
}

/* Calculates the divergence between each 'population[i] string
 *    and string 'desired'.
 * 'percpop' array becomes fitness level (between 0 and 1).
 * 'numpop' becomes for each letter which matches the letter of
 *    'desired' a 1, otherwhise a 0.
 * 'length holds the length of the organisms.
 */
void
calculatefitness (string population[], int length, string desired,
                  double percpop[], string numpop[])
{
    double counter = 0;
    string organism;
    string numorgan;
    double maxfit = 0;

    for (int i = 0; i < POP_COUNT; i++)
    {
        organism = population[i];
        for (int j = 0; j < length; j++)
        {
            if (organism.at (j) == desired.at (j))
            {
                organism[j] = {'1' };
            }
            else
            {
                organism[j] = { '0' };
            }
        }
        numpop[i] = organism;
    }
    for (int a = 0; a < 200; a++)
    {
        counter = 0;
        numorgan = numpop[a];
        for (int b = 0; b < length; b++)
        {
            if (numorgan.at (b) == '1')
            {
                counter++;
            }
        }
        percpop[a] = (counter) / (length);
    }
}

/* Fills mating pool from first -1-found with 'copy' counts
 * of value 'index'.
 */
void
otherticketinsert (int matingpool[], int index, int copy)
{
    for (int i = 0; i < MAX_POOL; i++)
    {
        if (matingpool[i] == -1)
        {
            for (int j = 0; j < copy; j++)
            {
                matingpool[i + j] = index;
            }
            break;
        }
    }
}


/* Fills matingpool[] with copys of percpop[], taking account
 * of the fitness oft the populations.
 */
void
buildMatingPool (double percpop[], int matingpool[], double normalpop[],
                 int factor)
{
    double largest = 0;
    int copy;

    for (int i = 0; i < POP_COUNT; i++)
    {
        if (largest < percpop[i])
        {
            largest = percpop[i];
        }
    }
    for (int j = 0; j < POP_COUNT; j++)
    {
        normalpop[j] = percpop[j] / largest;
    }
    for (int index = 0; index < POP_COUNT; index++)
    {
        copy = normalpop[index] * factor;
        otherticketinsert (matingpool, index, copy);
    }
}

/* Working is still unclear to me!
 */
string breed (string population[], int matingpool[],
              int desiredlength)
{

    int ticketsgiven;
    string child;
    int w, x, y, z;
    string a, b, c, d;

    for (int m = 0; m < MAX_POOL; m++)
    {
        if (matingpool[m] == -1)
        {
            ticketsgiven = (m - 1);
            break;
        }
        else
        {
            ticketsgiven = MAX_LOOP;
        }
    }
    int realparents[ticketsgiven] = { 0 };
    for (int n = 0; n < ticketsgiven; n++)
    {
        realparents[n] = matingpool[n];
    }
    w = realparents[rand () % ticketsgiven + 0];
    x = realparents[rand () % ticketsgiven + 0];
    y = rand () % (desiredlength - 1) + 0;
    a = population[w];
    b = population[x];
    a.erase ((y + 1), (desiredlength));
    b.erase (0, y + 1);
    c = a + b;
    child = c;
    
    return child;
}

/* Possibly mutates the string at a random position with a random value.
 */
string mutation (string child, int length)
{
    int x = rand () % 100 + 1;

    if (x <= 4)
    {
        char z = alphanum[rand () % 52];
        int y = rand () % (length - 1) + 0;
        child[y] = z;
    }
    return child;
}


void
resetMatingPool ( int matingpool[] )
{
    for (int idx = 0; idx < 2000; idx++)
    {
        matingpool[idx] = -1;
    }
}

int
main ()
{
    srand ( time ( nullptr ) );
    int counter;
    int i;
    int length;
    int factor = 10;
    string child;
    string mutatedchild;
    double largest = 0;
    string desired = { "" };
    
    int matingpool[2000];
    resetMatingPool (matingpool);
    

    double percpop[200] = { 0 };
    double normalpop[200] = { 0 };
    string population[200] = { "" };
    string numpop[200] = { "" };
    string children[200] = { "" };

    cout << "What would you like me to say?" << endl;
    getline (cin, desired);

    length = desired.size ();
    buildPopulation (population, length);

    for (int u = 0; u < 2000; u++)
    {
        counter++;
        calculatefitness (population, length, desired, percpop, numpop);
        resetMatingPool( matingpool );
        buildMatingPool (percpop, matingpool, normalpop, factor);

        for (int i = 0; i < 200; i++)
        {
            if (largest < percpop[i])
            {
                largest = percpop[i];
            }
        }

        cout << "Generation : " << counter 
             << ", Fitness : " << largest << endl;

        for (int k = 0; k < POP_COUNT; k++)
        {
            child = breed (population, matingpool, length);
            mutatedchild = mutation (child, length);
            children[k] = mutatedchild;
        }
        for (int j = 0; j < POP_COUNT; j++)
        {
            population[j] = children[j];
        }
        for(int p = 0 ; p < 200 ; p++)
        {
            if(percpop[p] == largest)
            {
                cout << population[p] << endl;
            }
        }
        if (largest >= 1.0) break;
    }
    if (counter < 2000)
    {
        cout << "Fitness of 1 was reached at generation : " << counter <<
         endl;
    }
    else
    {
        cout << "A Fitness of 1 was within " << MAX_LOOP
             << " loops never reached!\n";
    }
}
Found the error: Before 'largest' should be evaluated, there should be 'calculatefitness()' get invoked.
If not, then the array entries will in a wrong state.
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
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <array>
#include <cstring>

using namespace std;

const int MAX_LOOP = 2000;  // max count of iterations
const int POP_COUNT = 200;  // max count of organisms in the pool
constexpr int MAX_POOL = POP_COUNT * 10;  // max size of matingpool[]

/* ASCII-values of SPACE, A-Z, a-z.
 */
const char alphanum[53] =
{   32, 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, 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
};
 
/* Creates strings of length 'length', filled with randomly choosen
 * alpanumeric characters.
 */
void
buildPopulation (string population[], int length)
{   
    for (int i = 0; i < POP_COUNT; ++i)
    {
        string organism;
        
        for (int a = 1; a <= length; a++)
        {
            organism = organism + alphanum[rand () % 52];
        }
        population[i] = organism;
    }
}

/* Calculates the divergence between each 'population[i] string
 *    and string 'desired'.
 * 'percpop' array becomes fitness level (between 0 and 1).
 * 'numpop' becomes for each letter which matches the letter of
 *    'desired' a '1', otherwhise a '0'.
 * 'length holds the length of the organisms.
 */
void
calculatefitness (string population[], int length, string desired,
                  double percpop[], string numpop[])
{
    double counter = 0;  // count the matches inside 'organism'
    string organism;
    string numorgan;

    for (int i = 0; i < POP_COUNT; i++)
    {
        organism = population[i];
        for (int j = 0; j < length; j++)
        {
            if (organism.at (j) == desired.at (j))
            {
                organism[j] = { '1' };
            }
            else
            {
                organism[j] = { '0' };
            }
        }
        numpop[i] = organism;
    }
    for (int a = 0; a < 200; a++)
    {
        counter = 0;
        numorgan = numpop[a];
        for (int b = 0; b < length; b++)
        {
            if (numorgan.at (b) == '1')
            {
                counter++;
            }
        }
        percpop[a] = (counter) / (length);
    }
}

/* Fills mating pool from first -1-found with 'copy' counts
 * of value 'index'.
 */
void
otherticketinsert (int matingpool[], int index, int copy)
{
    for (int i = 0; i < MAX_POOL; i++)
    {
        if (matingpool[i] == -1)
        {
            for (int j = 0; j < copy; j++)
            {
                matingpool[i + j] = index;
            }
            break;
        }
    }
}

/* Fills matingpool[] with percpop[] indice, taking account
 * of the fitness oft the populations.
 */
void
buildMatingPool (double percpop[], int matingpool[], double normalpop[],
                 int factor)
{
    double largest = 0;
    int copy;

    for (int i = 0; i < POP_COUNT; i++)
    {
        if (largest < percpop[i])
        {
            largest = percpop[i];
        }
    }
    for (int j = 0; j < POP_COUNT; j++)
    {
        normalpop[j] = percpop[j] / largest;
    }
    for (int index = 0; index < POP_COUNT; index++)
    {
        copy = normalpop[index] * factor;
        otherticketinsert (matingpool, index, copy);
    }
}

/* Splices a string from two randomly choosen strings from pool ticket
 * to a new 'child' string.
 */
string breed (string population[], int matingpool[],
              int desiredlength)
{

    int ticketsgiven;   // fill count of matingpool[]
    string child;
    int w, x, y;
    string a, b;

    ticketsgiven = MAX_POOL;
    for (int m = 0; m < MAX_POOL; m++)
    {
        if (matingpool[m] == -1)
        {
            ticketsgiven = m;
            break;
        }
    }
    int realparents[ticketsgiven] = { 0 };
    for (int n = 0; n < ticketsgiven; n++)
    {
        realparents[n] = matingpool[n];
    }
    w = realparents[rand () % ticketsgiven];
    x = realparents[rand () % ticketsgiven];
    y = rand () % (desiredlength - 1);
    a = population[w];
    b = population[x];
    a.erase ((y + 1), (desiredlength));
    b.erase (0, y + 1);
    child = a + b;
    
    return child;
}

/* Possibly mutates the string at a random position with a random value.
 */
string mutation (string child, int length)
{
    int x = rand () % 100 + 1;

    if (x <= 4)
    {
        char z = alphanum[rand () % 52];
        int y = rand () % (length - 1) + 0;
        child[y] = z;
    }
    return child;
}


void
resetMatingPool ( int matingpool[] )
{
    for (int idx = 0; idx < 2000; idx++)
    {
        matingpool[idx] = -1;
    }
}

int
main ()
{
    srand ( time ( nullptr ) );
    int counter;       // counts the iterations
    int i;
    int idx;            // index to observe organisms at organism
    int length;         // string length
    int factor = 10;
    string child;
    string mutatedchild;
    double largest = 0;      //  largest percentage of matches
    string desired = { "" };  // desired string, goal
    
    int matingpool[2000];
    resetMatingPool (matingpool);
    

    double percpop[200] = { 0 };
    double normalpop[200] = { 0 };
    string population[200] = { "" };
    string numpop[200] = { "" };
    string children[200] = { "" };
    string probe;

    cout << "What would you like me to say?" << endl;
    getline (cin, desired);

    length = desired.size ();
    buildPopulation (population, length);
    calculatefitness (population, length, desired, percpop, numpop);

    for (int u = 0; u < 2000; u++)
    {
        counter++;
        resetMatingPool (matingpool);
        buildMatingPool (percpop, matingpool, normalpop, factor);


        for (int k = 0; k < POP_COUNT; k++)
        {
            child = breed (population, matingpool, length);
            population[k] = mutation (child, length);

        }
        calculatefitness (population, length, desired, percpop, numpop);
        for ( i = 0; i < 200; i++)
        {
            if (largest < percpop[i])
            {
                largest = percpop[i];
                probe = population[i];
                idx = i;
            }
        }   
/* DEBUG
        cout << population[idx] 
             <<", percpop:["<<idx<<"]: " << percpop[idx]
             <<  " string: " << probe
             << ", largest:" << largest << endl;
        
*/
        cout << "Generation : " << counter 
             << ", Fitness : " << largest << ", string: " << population[idx]
             << " (population["<<idx<<"])" << endl;

        if (largest >= 1.0) break;
    }
    if (counter < 2000)
    {
        cout << "Fitness of 1 was reached at generation : " 
             << counter <<  endl;
    }
    else
    {
        cout << "A Fitness of 1 was within " << MAX_LOOP
             << " loops never reached!\n";
    }
}
Last edited on
Topic archived. No new replies allowed.