Created
December 20, 2011 02:16
-
-
Save maxcountryman/1499922 to your computer and use it in GitHub Desktop.
Weasel in C
This file contains 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 <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <time.h> | |
char* ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; | |
char* TARGET = "ME THINKS IT IS LIKE A WEASEL"; | |
float RATE = 0.05; | |
int GENERATIONS = 250; | |
int ALPHABET_LEN = 27; | |
char* generate_candidate(char* string) { | |
char* output = (char*) malloc(strlen(TARGET) * sizeof(char)); | |
size_t i; | |
for(i = 0; i < strlen(string); i++) { | |
if ((rand() % 100) > (RATE * 100)) | |
output[i] = string[i]; | |
else { | |
output[i] = ALPHABET[rand() % ALPHABET_LEN]; | |
} | |
} | |
return output; | |
} | |
int check_fitness(char* string) { | |
size_t i; | |
int score = 0; | |
for(i = 0; i < strlen(string); i++) { | |
if (string[i] == TARGET[i]) { | |
score++; | |
} | |
} | |
return score; | |
} | |
char* run_generations(char* string) { | |
char* candidate; | |
char* winner; | |
int old_score = 0; | |
int new_score; | |
int i; | |
for(i = 0; i < GENERATIONS; i++) { | |
candidate = generate_candidate(string); | |
new_score = check_fitness(candidate); | |
if(new_score > old_score) { | |
winner = candidate; | |
old_score = new_score; | |
} | |
} | |
return winner; | |
} | |
char* random_seed() { | |
srand(time(NULL)); | |
char* string = (char*) malloc(strlen(TARGET) * sizeof(char)); | |
size_t i; | |
for(i = 0; i < strlen(TARGET); i++) { | |
string[i] = ALPHABET[rand() % ALPHABET_LEN]; | |
} | |
return string; | |
} | |
int main() { | |
char* output; | |
int counter = 0; | |
output = run_generations(random_seed()); | |
printf("%d: %s\n", counter, output); | |
counter++; | |
if(output != TARGET) | |
while(strcmp(output, TARGET)) { | |
output = run_generations(output); | |
printf("%d: %s\n", counter, output); | |
counter++; | |
} | |
else { | |
printf("%d: %s\n", counter, output); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hell yeah!