-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexer_1_basic.c
116 lines (103 loc) · 2.57 KB
/
exer_1_basic.c
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
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#define SIZE 20
#define N_MAX 1000
#define D 60
void crossover(int *parent1, int *parent2, int *child);
void mutation(int *child);
int calc_outcome(int *individual);
static double mut_rate = 1/(double)D;
int main() {
int t = 1;
int mu = SIZE; // the population size
int n = 1;
int P[mu][D];
int *parent1;
int *parent2;
int child[D];
int child_copy[D];
int outcome;
int *bsf; // best-so-far solution
srand((unsigned int)(time(NULL)));
// population initialization.
int i, j;
bsf = P[0];
for(i=0; i<mu; i++) {
for(j=0; j<D; j++) {
if((double)rand()/(double)RAND_MAX < 0.5 ) {
P[i][j] = 0;
} else {
P[i][j] = 1;
}
}
if(calc_outcome(P[i]) > calc_outcome(bsf)) {
bsf = P[i];
}
}
while(n <= N_MAX ) {
int index1 = rand()%mu;
int index2;
parent1 = P[index1];
while(index1 == (index2 = rand()%mu)) {
}
parent2 = P[index2];
crossover(parent1, parent2, child);
mutation(child);
outcome = calc_outcome(child);
n++;
// step 5, update the best-so-far solution
int bsf_out = calc_outcome(bsf);
if(outcome > bsf_out) {
for(j=0;j<D;j++) {
child_copy[j] = child[j];
}
bsf = child_copy;
}
// step 6, environmental selection
int tmp = rand()%mu;
if(outcome >= calc_outcome(P[tmp])) {
for(j=0;j<D;j++) {
P[tmp][j] = child[j];
}
}
t++;
printf("The best-so-far solution: ");
for(j=0;j<D;j++) {
printf("%d",bsf[j]);
}
printf("\tObjective function value: %d\n", bsf_out);
if(bsf_out == D) break;
}
return 0;
}
void crossover(int *parent1, int *parent2, int child[]) {
int j;
for(j=0;j<D;j++) {
if((double)rand()/(double)RAND_MAX < 0.5) {
child[j] = parent1[j];
} else {
child[j] = parent2[j];
}
}
}
void mutation(int *child) {
int j = 0;
for(;j<D;j++) {
if((double)rand()/(double)RAND_MAX < mut_rate) {
if(child[j] == 0) {
child[j] = 1;
} else {
child[j] = 0;
}
}
}
}
int calc_outcome(int *individual) {
int out = 0;
int j = 0;
for(;j<D;j++) {
out += individual[j];
}
return out;
}