static Osobnik generateChild(Osobnik first, Osobnik second) { double x, y; if (Abs(first.X) - Abs(second.X) >= 0) { x = (first.X - second.X) / 2; } else { x = (second.X - first.X) / 2; } if (Abs(first.Y) - Abs(second.Y) >= 0) { y = (first.Y - second.Y) / 2; } else { y = (second.Y - first.Y) / 2; } return(new Osobnik { X = x, Y = y, Dopasowanie = f(x, y) }); }
static Osobnik[] generatePopulation() { Osobnik[] population = new Osobnik[PopSize]; for (int i = 0; i < PopSize; i++) { double x = -XD + 2 * XD * rnd.NextDouble(); double y = -YD + 2 * YD * rnd.NextDouble(); population[i] = new Osobnik { X = x, Y = y, Dopasowanie = f(x, y) }; } return(population); }
static Osobnik[] crossPopulation(Osobnik[] population) { Osobnik[] newPopulation = new Osobnik[population.Length]; for (int i = 0; i < newPopulation.Length; i++) { int firstIndex = rnd.Next(population.Length); int secondIndex; do { secondIndex = rnd.Next(population.Length); } while (firstIndex == secondIndex); Console.WriteLine($"First: {firstIndex} --- Second: {secondIndex}"); newPopulation[i] = generateChild(population[firstIndex], population[secondIndex]); } return(newPopulation); }
static Osobnik[] selectNewPopulation(Osobnik[] population) { Osobnik[] newPopulation = new Osobnik[population.Length]; for (int i = 0; i < population.Length; i++) { int?enemyIndex = null; do { enemyIndex = rnd.Next(population.Length); } while (enemyIndex == i); if (population[i].Dopasowanie <= population[enemyIndex.Value].Dopasowanie) { newPopulation[i] = population[enemyIndex.Value]; } else { newPopulation[i] = population[i]; } } return(newPopulation); }