public void Mutation(int cIndex) { Chromosome chromosome = Chromosomes[cIndex]; if (chromosome == null) { return; } int type = GeneticUtils.GetRandom(3); ushort[] newArray = new ushort[chromosome.Values.Length]; chromosome.Values.CopyTo(newArray, 0); switch (type) { case 0: int index = GeneticUtils.GetRandom(ChromosomeSize); int end = GeneticUtils.GetRandom(ChromosomeSize - index) + index; for (int i = index; i < end; i++) { newArray[i] = AvailableValues.GetRandom(); } if (LeaveInitialValues) { Array.Copy(InitialValues, newArray, InitialValues.Length); } break; case 1: newArray[GeneticUtils.GetRandom(ChromosomeSize)] = 0; break; case 2: int randIndex1 = GeneticUtils.GetRandom(40); int randIndex2 = GeneticUtils.GetRandom(40); ushort temp = newArray[randIndex1]; newArray[randIndex1] = newArray[randIndex2]; newArray[randIndex2] = temp; break; } if (LeaveInitialValues) { Array.Copy(InitialValues, newArray, InitialValues.Length); } Chromosome newChromosome = new Chromosome(Sim, AvailableValues, ChromosomeSize, newArray); if (newChromosome.Fitness > chromosome.Fitness && !Contains(newChromosome)) { Chromosomes[cIndex] = newChromosome; } }
public void Crossover(Chromosome first, Chromosome second, int pos) { if (first == null || second == null) { return; } int index = GeneticUtils.GetRandom(ChromosomeSize); int size = GeneticUtils.GetRandom(ChromosomeSize - index); if (size == ChromosomeSize) { size = ChromosomeSize / 2; } ushort[] firstArray = new ushort[ChromosomeSize]; ushort[] secondArray = new ushort[ChromosomeSize]; Array.Copy(first.Values, firstArray, ChromosomeSize); Array.Copy(second.Values, secondArray, ChromosomeSize); Array.Copy(first.Values, index, secondArray, index, size); Array.Copy(second.Values, index, firstArray, index, size); Chromosome firstNew = new Chromosome(Sim, AvailableValues, firstArray.Length, firstArray); Chromosome secondNew = new Chromosome(Sim, AvailableValues, secondArray.Length, secondArray); if (LeaveInitialValues) { Array.Copy(InitialValues, firstNew.Values, InitialValues.Length); Array.Copy(InitialValues, secondNew.Values, InitialValues.Length); firstNew.Fitness = firstNew.Evaluate(); secondNew.Fitness = secondNew.Evaluate(); } if (firstNew.Fitness > Chromosomes[pos - 1].Fitness && !Contains(firstNew)) { Chromosomes[pos - 1] = firstNew; } if (secondNew.Fitness > Chromosomes[pos].Fitness && !Contains(secondNew)) { Chromosomes[pos] = secondNew; } }