Skip to content

Instantly share code, notes, and snippets.

@dmateos
Created November 3, 2009 05:30
Show Gist options
  • Save dmateos/224829 to your computer and use it in GitHub Desktop.
Save dmateos/224829 to your computer and use it in GitHub Desktop.
/*
* Practicing genetic algoritms
* Daniel Mateos
* Problem: find an equation out of 0-9 *+/- that comes up with 42
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GENES 32
#define CHROMOSOMES 32
struct chromosome {
int gene[GENES];
int fitness;
};
void gen_random_chromosomes(struct chromosome c[], int count);
void print_chromosomes(struct chromosome c[], int count);
float set_fitness(struct chromosome *c);
void gen_random_chromosomes(struct chromosome c[], int count) {
int i, y;
srand(time(NULL));
for(i = 0; i < count; i++) {
c[i].fitness = 0;
for(y = 0; y < GENES; y++) {
c[i].gene[y] = rand();
}
}
}
void print_chromosomes(struct chromosome c[], int count) {
int i, y;
for(i = 0; i < count; i++) {
printf("CHROMOSOME %d/%d fitness: %d\n", i, count, c[i].fitness);
for(y = 0; y < GENES; y++) {
printf("%x ", c[i].gene[y]);
}
printf("\n");
}
}
int main(int argc, char *argv[]) {
struct chromosome numbers[CHROMOSOMES];
gen_random_chromosomes(numbers, CHROMOSOMES);
print_chromosomes(numbers, CHROMOSOMES);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment