static void Main(string[] args) { Console.Write("Please enter a target phrase : \n"); membre.target = Console.ReadLine(); // Begin timing. stopwatch.Start(); Random r = new Random(); for (int i = 0; i < test.Length; i++)//initialize population { test[i] = new membre(); } for (int i = 0; i < test.Length; i++)//generate random genes for population { test[i].set_genes(r); } for (int i = 0; i < test.Length; i++) { test[i].calc_fitness(); } while (!is_finished) { create_pool(); reproduction(r); for (int i = 0; i < test.Length; i++) { test[i].calc_fitness(); } Console.Write(get_best()); if (is_finished == true) { stopwatch.Stop(); Console.Write("\n Time elapsed : {0}", stopwatch.Elapsed); } } Console.ReadKey(); }
public static void reproduction(Random r) { for (int i = 0; i < test.Length; i++) { int index_parent_a = r.Next(pool.Count); int index_parent_b = r.Next(pool.Count); membre ma = pool[index_parent_a]; membre mb = pool[index_parent_b]; membre child = ma.crossover(mb, r); // crossover child.mutate(r); //mutation test[i] = child; } generation++; }
public membre crossover(membre partner, Random r) { membre c = new membre(); int midpoint = r.Next(genes.Length); for (int i = 0; i < genes.Length; i++) { if (i > midpoint) { c.genes[i] = genes[i]; } else { c.genes[i] = partner.genes[i]; } } return(c); }