/** * main program */ int main (void) { float cpu1,cpu2; cpu1 = ((float) clock())/CLOCKS_PER_SEC; srand (time (NULL)); ga_struct *population = malloc (sizeof (ga_struct) * POPSIZE); ga_struct *beta_population = malloc (sizeof (ga_struct) * POPSIZE); init_population (population, beta_population); char *gen_str = population[0].gen; char element[5] = "\0"; strncpy (element, gen_str, 4); //if (strcmp ("0000", element) == 0) int index = 0; for (; index < POPSIZE; index++) { cal_fitness (population); sort_by_fitness (population); // print current best individual printf ("binary string: %s - fitness: %d\n", population[0].gen, population[0].fitness); if (population[0].fitness == 0) { //~ print equation decode_gen (&population[0]); break; } mate (population, beta_population); swap (&population, &beta_population); } free_population (population); free_population (beta_population); cpu2 = ((float) clock())/CLOCKS_PER_SEC; printf("Execution time (s) = %le\n",cpu2-cpu1); return 0; }
int main(void) { int popsize = 0, max_iter = 0; char target[128]; char str_buffer[64]; FILE *fp = fopen("conf", "r"); fscanf(fp, "%s %d", &str_buffer, &popsize); fscanf(fp, "%s %s", &str_buffer, &target); fscanf(fp, "%s %d", &str_buffer, &max_iter); int target_length = strlen(target); srand(time(NULL)); printf("Genetic Algorithm to find a user-specified target string\n"); printf("Quinn Thibeault - 2015\n"); printf("Target string: %s Length: %d\n", target, target_length); printf("Population Size: %d\n", popsize); printf("Maximum Iterations: %d\n\n", max_iter); struct organism population[POPSIZE], buffer[POPSIZE]; struct organism *p_pop = population; struct organism *p_buf = buffer; init_population(p_pop, target_length); init_population(p_buf, target_length); gen_random_population(p_pop, target_length); for(int i=0;i<ITER; ++i){ calc_fitness(p_pop, target, target_length); sort_by_fitness(p_pop); //print_most_fit(p_pop); if(p_pop->fitness == 0){ printf("Number of generations: %d\n", i); break; } regen_population(p_pop, p_buf, target_length); swap(&p_pop, &p_buf); } print_most_fit(p_pop); return 0; }
void SolverEvolver::evolve() { sort_by_fitness(); std::vector<Individual> child_population; while (child_population.size() < population_size_) { Individual& c0 = select(); Individual& c1 = select(); if (rand_.NextBool(combination_p_)) { crossover(c0.genome, c1.genome); } mutate(c0.genome); mutate(c1.genome); child_population.push_back(c0); child_population.push_back(c1); } population_ = child_population; initate_population(); }