Last active
August 29, 2015 14:14
-
-
Save maekawatoshiki/dae63506c566e720311e to your computer and use it in GitHub Desktop.
Genetic_Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdio> | |
#include <cstdlib> | |
#include <cstring> | |
#include <cmath> | |
#include <ctime> | |
using namespace std; | |
#define MAX 20 | |
#define MAX_S 0xFFFF | |
int ge[MAX][MAX_S]; | |
int child1[MAX_S]; | |
int child2[MAX_S]; | |
int maxes[MAX]; | |
char msg[MAX_S] = { 0 }; | |
int tmp[MAX_S] = { 0 }; | |
int main() | |
{ | |
cin.getline(msg, 0xFFFF); | |
int msgsz = strlen(msg); | |
int i, k, j; | |
int min = 0, min2 = 0, minNumber = 0; | |
srand(time(0)); | |
for (i = 0; i<MAX; i++) | |
for (k = 0; k<msgsz; k++) | |
ge[i][k] = 33 + rand() % 127; | |
for (j = 0;; j++) | |
{ | |
memset(maxes, 0, sizeof(int) * MAX); | |
for (i = 0; i<MAX; i++) | |
for (k = 0; k<msgsz; k++) | |
maxes[i] += (msg[k] - ge[i][k]) * (msg[k] - ge[i][k]); | |
if (j % 100 == 0) | |
{ | |
for (i = 0; i<MAX; i++) | |
{ | |
for (k = 0; k<msgsz; k++) | |
/* ターミナルからBELLがなるときはコメントをはずす */ | |
if (ge[i][k] != 0x07) printf("%c", ge[i][k]); | |
putchar('\n'); | |
} | |
} | |
for (i = 0; i<MAX; i++) | |
{ | |
if (maxes[i] == 0) | |
{ | |
for (k = 0; k<msgsz; k++) | |
/*if (ge[i][k] != 0x07)*/ printf("%c", ge[i][k]); | |
putchar('\n'); | |
} | |
} | |
for (i = 0; i < MAX; i++) | |
{ | |
min2 = min = maxes[i]; | |
for (k = i; k < MAX; k++) | |
{ | |
min2 = maxes[k]; | |
if(min2 < min) | |
{ | |
minNumber = k; | |
min = min2; | |
if( 0 == min ) | |
{ | |
cout << j << endl; | |
return 0; | |
} | |
} | |
} | |
memcpy(&ge[i], &ge[minNumber], sizeof(int) * msgsz); | |
} | |
// 一様交叉 | |
for (i = 0; i < msgsz; i++) | |
{ | |
if( rand() % 2 ) child1[i] = ge[0][i]; | |
else child1[i] = ge[1][i]; | |
if( rand() % 2 ) child2[i] = ge[0][i]; | |
else child2[i] = ge[1][i]; | |
} | |
memcpy(&ge[MAX-1 -0], child1, sizeof(int) * msgsz); | |
memcpy(&ge[MAX-1 -1], child2, sizeof(int) * msgsz); | |
memcpy(&ge[MAX-1 -2], child1, sizeof(int) * msgsz); | |
// 突然変異 | |
for (i = 0; i < MAX / 2; i++) | |
ge[rand() % MAX][rand() % msgsz] += rand() % 2 ? -1 : 1; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment