/* * "Main" function of the program. It runs for the entire generation count, generating children, * culling the population, and outputting the stats. */ public void run() { string parent1; string parent2; string child; Money coinList = new Money(); for (int i = 0; i < numberOfVariables; i++) //Get the input { getInput(i); } initialize(); //Initialize the population for (int genCount = 0; genCount < generations; genCount++) { newPopValues(); //update the population values. survivorCount = 0; for (int childrenCount = 0; childrenCount < numOfChildren; childrenCount++) { // Select 2 Random Parents, perform crossover parent1 = population[rand.Next() % popSize]; parent2 = population[rand.Next() % popSize]; child = crossover(parent1, parent2); //random position, front half of a goes to child, back half of b goes to child if ((rand.Next() % 100) < mutationRate) //percentage of chance for mutation child = mutate(child); //pick random spot, replace value with new random value // evaluate child values[popSize + childrenCount] = coinList.getValue(child); fitness[popSize + childrenCount] = evaluateFitness(values[popSize + childrenCount]); // add child to population population[popSize + childrenCount] = child; } //sort population by fitness sort(0, fitness.Count - 1); //elitism - copies certain number of top choices to survivors elitistSelection(); //survivor selection - tournament (do until survivor is filled) while (survivorCount < popSize) { survivors[survivorCount] = population[tournamentSelection()]; survivorCount++; } //population = survivors for (int i = 0; i < survivorCount; i++) { population[i] = survivors[i]; } //report stats - best individual, average fitness level outputStats(genCount); } //Memory Management population.Clear(); values.Clear(); survivors.Clear(); fitness.Clear(); }
/* * This function is called to compute the values and the fitness of the * population size. */ void newPopValues() { Money coinList = new Money(); for (int index = 0; index < popSize; index++) { values[index] = coinList.getValue(population[index]); fitness[index] = evaluateFitness(values[index]); } }