private Individ RightUnitGreegy(int n = 0) //Прямой удельный жадный алгоритм, начинающий поиск с n-ой компании { Individ data = new Individ(); int limit = n + numberOfCompany - 1; int counter = numberOfAttachmentSizes - 1; int currentPos; while ((counter > 0) && (n < limit)) { double maxGain = 0; int pos = 0; currentPos = n % numberOfCompany; for (int j = 1; j < counter + 1; j++) { double gain = (double)tableOfOffers[currentPos, j] / sizeOfAttachment[j]; if (gain >= maxGain) { maxGain = gain; pos = j; } } data.Set(currentPos, pos); counter -= pos; n++; } data.Set(limit % numberOfCompany, counter); return(data); }
private Individ[] ProportionalSelection(Individ[] population, Individ[] child, int populationSize, double averageFitness) //Работает не очень, быстро сходится { Individ[] newPopulation = new Individ[populationSize]; int counter = 0; for (int i = 0; i < populationSize && counter < populationSize; i++) { if (averageFitness < population[i].GetFitness()) { newPopulation[counter++] = new Individ(population[i]); } } for (int i = 0; i < populationSize * 2 && counter < populationSize; i++) { if (averageFitness < child[i].GetFitness()) { newPopulation[counter++] = new Individ(child[i]); } } while (counter < populationSize) { newPopulation[counter++] = new Individ(child[rnd.Next(populationSize * 2)]); } return(newPopulation); }
private Individ LeftUnitGreedy(int n = 0) //Обратный удельный жадный алгоритм, начинающий поиск с n-ой компании { Individ data = new Individ(); int counter = numberOfAttachmentSizes - 1; n %= numberOfCompany; int currentPos = (n - 1 + numberOfCompany) % numberOfCompany; while ((counter > 0) && (currentPos != n)) { double maxGain = 0; int pos = 0; for (int j = 1; j < counter + 1; j++) { double gain = (double)tableOfOffers[currentPos, j] / sizeOfAttachment[j]; if (gain >= maxGain) { maxGain = gain; pos = j; } } data.Set(currentPos, pos); counter -= pos; currentPos = (currentPos - 1 + numberOfCompany) % numberOfCompany; } data.Set(currentPos, counter); return(data); }
public Individ(Individ a) { genotype = new int[NoC]; for (int i = 0; i < NoC; i++) { genotype[i] = a.genotype[i]; } UpdateFitness(); }
private Individ UniformCrossover(Individ[] population, int populationSize) { Individ a = new Individ(); int firstParent = rnd.Next(populationSize); int secondParent = rnd.Next(populationSize); a.UniformCrossover(population[firstParent], population[secondParent], rnd); return(a); }
public Individ(Individ a) { code = new bool[fullLength]; for (int i = 0; i < fullLength; i++) { code[i] = a.code[i]; } profit = a.profit; resources = a.resources; fitness = a.fitness; }
public void GreedProportional() { Individ[] solutionPair = new Individ[2]; for (int i = 0; i < 2; i++) { solutionPair[i] = new Individ(); } solutionPair[0] = RightUnitGreegy(); solutionPair[1] = LeftUnitGreedy(); solutionPair[0].Print(); solutionPair[1].Print(); }
public Individ(Individ a, Individ b, int pos) //Crossover { genotype = new int[NoC]; for (int i = 0; i < pos; i++) { genotype[i] = a.genotype[i]; } for (int i = pos; i < NoC; i++) { genotype[i] = b.genotype[i]; } UpdateFitness(); }
public void RandSolution() { int numberOfSolutions = 5; Individ[] RandSolution = new Individ[numberOfSolutions]; Console.WriteLine("Случайные решения: "); for (int i = 0; i < numberOfSolutions; i++) { RandSolution[i] = new Individ(rnd, rnd.Next(1, 2)); RandSolution[i].Print(); } Console.WriteLine("Конец случайных решений!"); }
public void UniformCrossover(Individ firstParent, Individ secondParent, Random rnd) { for (int i = 0; i < NoC; i++) { if (rnd.Next(2) == 0) { genotype[i] = firstParent.genotype[i]; } else { genotype[i] = secondParent.genotype[i]; } } UpdateFitness(); }
public Individ(Individ a, Individ b, int pos) //Конструктор особи при кроссовере { code = new bool[fullLength]; int codePos = pos * shortLength; for (int i = 0; i < codePos; i++) { code[i] = a.code[i]; } for (int i = codePos; i < fullLength; i++) { code[i] = b.code[i]; } UpdateFitness(); }
public DataCase(int a, int b, int r) { rnd = new Random(); if (r % (b - 1) == 0) { MemoryAllocation(a, b, r); RandInitValues(); } else { Console.WriteLine("Недопустимые значения, инициализация по умолчанию!\n"); MemoryAllocation(); BaseInitValues(); //Метод инициализации проверочными значениями } Individ.StaticInit(numberOfCompany, numberOfAttachmentSizes, resources, tableOfOffers, sizeOfAttachment); }
public void GreedyAlg() { Individ[] solutionPair = new Individ[2]; for (int i = 0; i < 2; i++) { solutionPair[i] = new Individ(); } int counter = numberOfAttachmentSizes; for (int i = 0; i < numberOfCompany; i++) { int maxGain = -sizeOfAttachment[numberOfAttachmentSizes - 1]; int pos = -1; for (int j = 0; j < counter; j++) { int gain = tableOfOffers[i, j] - sizeOfAttachment[j]; if (gain >= maxGain) { maxGain = gain; pos = j; } } solutionPair[0].Set(i, pos); counter -= pos; } counter = numberOfAttachmentSizes; for (int i = numberOfCompany - 1; i >= 0; i--) { int maxGain = -sizeOfAttachment[numberOfAttachmentSizes - 1]; int pos = -1; for (int j = 0; j < counter; j++) { int gain = tableOfOffers[i, j] - sizeOfAttachment[j]; if (gain >= maxGain) { maxGain = gain; pos = j; } } solutionPair[1].Set(i, pos); counter -= pos; } solutionPair[0].Print(); solutionPair[1].Print(); }
private Individ[] WheelRotation(Individ[] population, int populationSize, int sumFitness) //Уже лучше, но не идеал { Individ[] newPopulation = new Individ[populationSize]; for (int i = 0; i < populationSize; i++) { int rangePoint = rnd.Next(sumFitness); //Не нравится поиск, переписать, основываясь на лабе по ген алгоритмам double topRange = 0; //Конкретно не нравится интовый поиск по даблам for (int j = 0; j < populationSize * 3; j++) { topRange += population[j].GetFitness(); if (rangePoint < topRange) { newPopulation[i] = new Individ(population[j]); break; } } } return(newPopulation); }
private Individ[] WheelRotation(Individ[] population, int populationSize, int sumFitness) { Individ[] newPopulation = new Individ[populationSize]; for (int i = 0; i < populationSize; i++) { int rangePoint = rnd.Next(sumFitness); double topRange = 0; for (int j = 0; j < populationSize * 3; j++) { topRange += population[j].GetFitness(); if (rangePoint < topRange) { newPopulation[i] = new Individ(population[j]); break; } } } return(newPopulation); }
private Individ SinglepointCrossover(Individ[] population, int populationSize) { Individ a = new Individ(population[rnd.Next(populationSize)], population[rnd.Next(populationSize)], rnd.Next(1, numberOfCompany)); return(a); }
public void GeneticAlg() //Отвратительно работает, когда количество компаний больше количества предложений, т.е. когда в оптимальном генотипе есть множество нулей { int populationSize = numberOfAttachmentSizes * numberOfCompany; Individ.StaticInit(numberOfCompany, numberOfAttachmentSizes, resources, tableOfOffers, sizeOfAttachment); Console.WriteLine("Стартовая популяция: "); Individ[] population = new Individ[populationSize]; for (int i = 0; i < populationSize; i++) { population[i] = new Individ(rnd, rnd.Next(2)); //Случайная генерация стартовой популяции //population[i].Print(); } Console.WriteLine("Конец стартовой популяции"); int counter = 0; while (counter++ < 100) { double sumFitness = 0; Individ[] child = new Individ[populationSize * 3]; for (int i = 0; i < populationSize; i++) { child[i] = new Individ(population[i]); sumFitness += child[i].GetFitness(); } for (int i = populationSize; i < populationSize * 3; i++) //Создание потомков путем одноточечного кроссовера { child[i] = Crossover(population, populationSize); //Можно вставить формулу, но так красивее sumFitness += child[i].GetFitness(); } for (int i = 0; i < populationSize / 10; i++) { sumFitness += child[rnd.Next(populationSize * 3)].Mutation(rnd); } double averageFitness = sumFitness / (populationSize * 3); population = WheelRotation(child, populationSize, Convert.ToInt32(Math.Ceiling(sumFitness))); //Console.WriteLine("Потомки:"); //for (int i = 0; i < populationSize * 2; i++) // child[i].Print(); //population = ProportionalSelection(population, child, populationSize, averageFitness); //Console.WriteLine("Суммарная приспособленность равна: " + sumFitness); //Console.WriteLine("Средняя приспособленность: " + averageFitness); //Округляет вверх всегда //for (int i = 0; i < populationSize; i++) // population[i].Print(); } //for (int i = 0; i < populationSize; i++) // population[i].Print(); Console.WriteLine("Наилучшее найденное решение: "); population[FindBest(population, populationSize)].Print(); }
public void GeneticAlg(System.Diagnostics.Stopwatch record) //Отвратительно работает, когда количество компаний больше количества предложений, т.е. когда в оптимальном генотипе есть множество нулей { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); int populationSize = numberOfAttachmentSizes; Individ[] population = new Individ[populationSize]; for (int i = 0; i < populationSize; i++) { population[i] = new Individ(); } //RandPopulation(population, populationSize); //Случайная генерация стартовой популяции GreedyPopulation(population, populationSize); //Генерация стартовой популяции жадными алгоритмами со сдвигом //for (int i = 0; i < populationSize; i++) // population[i].Print(1); //int testcount = 0; int iterationCounter = 0; while ((stopwatch.ElapsedMilliseconds < record.ElapsedMilliseconds / 2) /*| testcount++ < 100*/) { double sumFitness = 0; Individ[] child = new Individ[populationSize * 3]; for (int i = 0; i < populationSize; i++) { child[i] = new Individ(population[i]); sumFitness += child[i].GetFitness(); } for (int i = populationSize; i < populationSize * 3; i++) //Создание потомков путем одноточечного кроссовера { if (rnd.Next(2) == 0) { child[i] = SinglepointCrossover(population, populationSize); } else { child[i] = UniformCrossover(population, populationSize); } sumFitness += child[i].GetFitness(); } for (int i = 0; i < populationSize / 10; i++) { sumFitness += child[rnd.Next(populationSize, populationSize * 3)].Mutation(rnd); //Мутации производятся только среди потомков } double averageFitness = sumFitness / (populationSize * 3); //Console.WriteLine(sumFitness); //population = WheelRotation(child, populationSize, sumFitness); //population = WheelRotation(child, populationSize, Convert.ToInt32(Math.Ceiling(sumFitness))); //Старая версия //Console.WriteLine("Потомки:"); //for (int i = 0; i < populationSize * 2; i++) // child[i].Print(); population = ProportionalSelection(population, child, populationSize, averageFitness); //Console.WriteLine("Суммарная приспособленность равна: " + sumFitness); //Console.WriteLine("Средняя приспособленность: " + averageFitness); //Округляет вверх всегда //for (int i = 0; i < populationSize; i++) // population[i].Print(); iterationCounter++; } stopwatch.Stop(); Console.WriteLine("Количество итераций: {0}\nНаилучшее найденное решение: ", iterationCounter); population[FindBest(population, populationSize)].Print(); //for (int i = 0; i < populationSize; i++) // Console.WriteLine(population[i].GetFitness()); }