private void btnFinish_Click(object sender, EventArgs e) { populationSize = Convert.ToInt32(numPop.Value); crossoverProb = Convert.ToDouble(numCross.Value); mutateProb = Convert.ToDouble(numMutate.Value); maxGeneration = Convert.ToInt32(numGeneration.Value); string result = ""; KnapsackGA.Init(items, capacity); string bestsol = RunGA(populationSize, mutateProb, crossoverProb, maxGeneration, 0.9); int value = 0; int weight = 0; for (int i = 0; i < bestsol.Length; i++) { if (bestsol[i] == '1') { result += (i + 1) + " "; value += items[i].v; weight += items[i].w; } } result += ", Fitness: " + value + ", Weight: " + weight; lbBestSolution.Text = result; lbBestSolution.Visible = true; btnFinish.Enabled = false; }
public string RunGA(int popSize, double mut, double cross, int maxGen, double percent) { List <string> pop = KnapsackGA.generate(popSize); fitness = KnapsackGA.getFitness(pop); Stopwatch swObj = new Stopwatch(); swObj.Start(); while (!KnapsackGA.test(fitness, percent) && generation < maxGen) { generation++; pop = KnapsackGA.newPopulation(pop, fitness, mut, cross); fitness = KnapsackGA.getFitness(pop); best = KnapsackGA.BestFit(fitness); } swObj.Stop(); lbGeneration.Text = generation.ToString(); lbTime.Text = swObj.Elapsed.ToString(); lbTime.Visible = true; chart1.Visible = true; RunChart(); dt = new DataTable(); dt.Columns.Add("Chronosome", typeof(string)); dt.Columns.Add("Fitness", typeof(int)); for (int i = 0; i < pop.Count; i++) { DataRow row = dt.NewRow(); row["Chronosome"] = pop[i]; row["Fitness"] = fitness[i]; dt.Rows.Add(row); } dgvPopulation.DataSource = dt; return(KnapsackGA.selectElite(pop, fitness)); }