public Population() { Random rand = new Random(); curPopulation = new List <Chromosome>(); byte[] temp = new byte[Program.size]; int sum; int randomN; for (int i = 0; i < Program.n - 1; i++) { sum = 0; for (int j = 0; j < Program.size; j++) { randomN = Convert.ToByte(rand.Next(0, 2)); if (randomN == 1) { if (sum + Program.weight[j] <= Program.capacity) { sum += Program.weight[j]; temp[j] = 1; } else { temp[j] = 0; } } else { temp[j] = 0; } } Chromosome chromosome = new Chromosome(); Array.Copy(temp, chromosome.genes, temp.Length); chromosome.calcFitness(); curPopulation.Add(chromosome); } Dictionary <int, double> ratios = new Dictionary <int, double>(); for (int i = 0; i < Program.weight.Count; i++) { ratios[i] = Program.value[i] / Convert.ToDouble(Program.weight[i]); } byte[] knapsack = new byte[Program.weight.Count]; sum = 0; foreach (KeyValuePair <int, double> item in ratios.OrderByDescending(key => key.Value)) { if (sum + Program.weight[item.Key] <= Program.capacity) { sum += Program.weight[item.Key]; knapsack[item.Key] = 1; } else { break; } } Chromosome chromosomeBest = new Chromosome(); Array.Copy(knapsack, chromosomeBest.genes, temp.Length); chromosomeBest.calcFitness(); curPopulation.Add(chromosomeBest); }