/// <inheritdoc/> public void Swap(int iswap1, int iswap2) { FourBitGene temp = this.data[iswap1]; this.data[iswap1] = this.data[iswap2]; this.data[iswap2] = temp; }
private FourBitCustomGenome PerformErrorlessSmartCustomMutation(FourBitCustomGenome parent) { try { FourBitCustomGenome offSpring = new FourBitCustomGenome(parent.Data.Length); var random = new Random(); var mutateIndex1 = random.Next(1, parent.Data.Length); // random number is between 0 and for (var geneIndex = 0; geneIndex < parent.Size; geneIndex++) { if (geneIndex != mutateIndex1) { offSpring.Data[geneIndex] = parent.Data[geneIndex]; } else { // mutation FourBitGene geneToMutate = parent.Data[geneIndex]; var bitZeroCount = geneToMutate.Gene.Count(x => x == 0); var randomNumber = random.Next(1, 101); // random number is between 0 and 100 switch (bitZeroCount) { case 0: { offSpring.Data[geneIndex] = geneToMutate; break; } case 1: { var remainder = randomNumber % 4; // either zero or one or two or three int [] mutatedGene = remainder == 0 ? new[] { 0, 0, 0, 1 } : remainder == 1 ? new[] { 0, 0, 1, 0 } : remainder == 2 ? new[] { 0, 1, 0, 0 } : new[] { 1, 0, 0, 0 }; offSpring.Data[geneIndex] = new FourBitGene { Gene = mutatedGene }; break; } case 2: { var remainder = randomNumber % 3; // either zero or one or two int[] mutatedGene = remainder == 0 ? new[] { 0, 0, 1, 1 } : remainder == 1 ? new[] { 0, 1, 1, 0 } : new[] { 1, 1, 0, 0 }; offSpring.Data[geneIndex] = new FourBitGene { Gene = mutatedGene }; break; } case 3: { var remainder = randomNumber % 2; // either zero or one int[] mutatedGene = remainder == 0 ? new[] { 0, 1, 1, 1 } : new[] { 1, 1, 1, 0 }; offSpring.Data[geneIndex] = new FourBitGene { Gene = mutatedGene }; break; } case 4: { offSpring.Data[geneIndex] = geneToMutate; break; } default: { offSpring.Data[geneIndex] = geneToMutate; break; } } } } return(offSpring); } catch (Exception e) { Console.WriteLine(e); throw; } }