public void GreedyCrossoverTest() { IChromosome<int> a = new DigitalChromosome().GenerateFromArray(new int[] { 4, 2, 3, 1 }); IChromosome<int> b = new DigitalChromosome().GenerateFromArray(new int[] { 1, 4, 3, 2 }); int[,] matrix = new int[4, 4] { { 0, 2, 3, 4}, { 1, 0, 2, 3}, { 1, 2, 0, 5}, { 3, 7, 6, 0} }; GreedyCrossover cross = new GreedyCrossover(4, 2, matrix); IChromosome<int>[] res = cross.Crossover(a, b); IChromosome<int>[] exp = new IChromosome<int>[2] { new DigitalChromosome().GenerateFromArray(new int[] { 4, 3, 1, 2 }), new DigitalChromosome().GenerateFromArray(new int[] { 2, 1, 4, 3 }) }; CollectionAssert.AreEqual(res, exp); }
private void Go_Click(object sender, EventArgs e) { //initialize var int cLength = Convert.ToInt32(chromoLength.Text); EliteSelection<int> sel2 = new EliteSelection<int>(0); RouletteSelection<int> sel1 = new RouletteSelection<int>(); GreedyCrossover cros = new GreedyCrossover(-1, -1, matrix); GoldenMutation<int> mut = new GoldenMutation<int>(cLength); pop = new Population<int>(mut, cros, sel1, sel2, x => 1 / cros.CalcFitness(x), Convert.ToDouble(mProb.Text), Convert.ToDouble(cProb.Text)); maxF = new double[Convert.ToInt32(expCount.Text), Convert.ToInt32(iterCount.Text) + 1]; avgF = new double[Convert.ToInt32(expCount.Text), Convert.ToInt32(iterCount.Text) + 1]; double min = 100500; // Hi to Max )) string bestChromo = null; //experiments for (int i = 0; i < Convert.ToInt32(expCount.Text); ++i) { //initial chromosomes Trace.WriteLine("experiment #" + (i + 1).ToString()); Trace.Indent(); ChromosomesFromArray(); maxF[i, 0] = Math.Round(1 / pop.GetMaxFitness()); avgF[i, 0] = 1 / pop.GetPopulationFitness(); Trace.WriteLine("initial best fitness = " + Math.Round((1 / pop.GetMaxFitness())).ToString()); Trace.WriteLine("initial avg fitness = " + (1 / pop.GetPopulationFitness()).ToString()); Trace.WriteLine("initia;best fitness chromo = " + pop.GetMaxChromo()); // iterations for (int j = 0; j < Convert.ToInt32(iterCount.Text); ++j) { Trace.WriteLine("iteration #" + (j + 1).ToString()); Trace.Indent(); pop.Iteration(); maxF[i, j + 1] = Math.Round(1 / pop.GetMaxFitness()); avgF[i, j + 1] = 1 / pop.GetPopulationFitness(); Trace.WriteLine(" best fitness = " + Math.Round((1 / pop.GetMaxFitness())).ToString()); Trace.WriteLine("avg fitness = " + (1 / pop.GetPopulationFitness()).ToString()); Trace.WriteLine("best fitness chromo = " + pop.GetMaxChromo()); Trace.Unindent(); } if (Math.Round(1 / pop.GetMaxFitness()) < min) { min = Math.Round(1 / pop.GetMaxFitness()); bestChromo = pop.GetMaxChromo(); } Trace.Unindent(); } answer.Text = "Best Path: " + bestChromo + "Path Length" + min.ToString(); }