#ifndef lint static char *rcsid = "$Header: /tmp_mnt/vida/disks/disk5/Users/terry/r/gassy/RCS/selectors.c,v 1.3 1992/10/09 06:43:50 terry Exp terry $"; #endif #include "types.h" VOID * roulette_selection(reproducers, nselections, context) INT *reproducers; INT *nselections; CONTEXT* context; { register INT i; FITNESS total_fitness = context->total_fitness; register INT population_size = context->population_size; /* * If everyone is totally unfit, choose them at random. */ if (total_fitness == (FITNESS)0){ for (i = 0; i < population_size; i++){ reproducers[i] = uniform(context->population_size); } *nselections = population_size; return 0; } /* * Select the machines that will reproduce. */ for (i = 0; i < population_size; i++){ register FITNESS where = (FITNESS) (uniform((INT) total_fitness) + (FITNESS) 1); /* produces 1..total_fitness */ register INT reproducer = 0; while (where > (FITNESS) 0){ where -= context->population[reproducer].fitness; reproducer++; } reproducers[i] = reproducer - 1; } *nselections = population_size; return 0; } #define TOURNAMENT_SELECTION_WITH_REPLACEMENT VOID * tournament_selection(reproducers, nselections, context) INT *reproducers; INT *nselections; CONTEXT* context; { register INT i; register INT population_size = context->population_size; /* Select the strings that will survive via a tournament. */ for (i = 0; i < population_size; i++){ register INT a = uniform(population_size); register INT b; #if defined(TOURNAMENT_SELECTION_WITH_REPLACEMENT) b = uniform(population_size); if (a == b){ reproducers[i] = a; continue; } #else do { b = uniform(population_size); } while (a == b); #endif if (DO_TOURNAMENT){ /* Choose the most fit of the two. */ if (context->population[a].fitness > context->population[b].fitness){ reproducers[i] = a; } else { reproducers[i] = b; } } else { /* Choose the less fit of the two. */ if (context->population[a].fitness > context->population[b].fitness){ reproducers[i] = b; } else { reproducers[i] = a; } } } *nselections = population_size; return 0; } VOID * select_all(reproducers, nselections, context) INT *reproducers; INT *nselections; CONTEXT* context; { register INT i; register INT population_size = context->population_size; for (i = 0; i < population_size; i++){ reproducers[i] = i; } *nselections = population_size; return 0; }