Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
- int randomNumber(int high) {
- return rand() % high;
- }
- int generateOffspring(char* currentGen, int currentLen, char* letters, char** offspring, unsigned long children, int probability) {
- for (unsigned int i = 0; i < children; i++) {
- for (unsigned int c = 0; c < currentLen; c++) {
- if (randomNumber(probability) < 1) {
- offspring[i][c] = letters[randomNumber(27)];
- }
- else {
- offspring[i][c] = currentGen[c];
- }
- }
- }
- return 0;
- }
- int findLeastDistance(char* string, char** strings, int len, int count) {
- unsigned int matches = 0;
- unsigned int bestMatches = 0;
- unsigned int bestMatch = 0;
- for (unsigned int i = 0; i < count; i++) {
- for (unsigned int c = 0; c < len; c++) {
- if (string[c] == strings[i][c]) {
- matches++;
- }
- }
- if (matches > bestMatches) {
- bestMatches = matches;
- bestMatch = i;
- }
- matches = 0;
- }
- return bestMatch;
- }
- int main(int argc, char *argv[]) {
- system("PAUSE");
- time_t t;
- srand((unsigned)time(&t));
- unsigned int probability;
- if (argc == 2) {
- probability = (int)argv[1];
- }
- else {
- probability = 10000;
- }
- unsigned int children = 100;
- char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
- char target[] = "METHINKS IT IS LIKE A WEASEL";
- char currentGen[29];
- for (unsigned int i = 0; i < 29; i++) {
- currentGen[i] = letters[randomNumber(27)];
- }
- char** offspring[children];
- for (unsigned int i = 0; i < children; i++) {
- offspring[i] = malloc(29);
- }
- unsigned int bestMutation;
- unsigned int counter = 0;
- for (;;) {
- generateOffspring(currentGen, 28, letters, offspring, children, probability);
- bestMutation = findLeastDistance(target, offspring, 28, children);
- if (strcmp(currentGen, offspring[bestMutation])) {
- printf("Gen %d: %s\n", counter, offspring[bestMutation]);
- }
- strcpy(currentGen, offspring[bestMutation]);
- if (!strcmp(currentGen, target)) {
- break;
- }
- counter++;
- }
- for (unsigned int i = 0; i < children; i++) {
- free(offspring[i]);
- }
- free(currentGen);
- printf("\nEnd\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement