giacomelli / GeneticSharp

GeneticSharp is a fast, extensible, multi-platform and multithreading C# Genetic Algorithm library that simplifies the development of applications using Genetic Algorithms (GAs).
MIT License
1.27k stars 332 forks source link

AlternatingPositionCrossover throw IndexOutOfRangeException #61

Closed dxball closed 5 years ago

dxball commented 5 years ago

Describe the bug Using the AlternatingPositionCrossover cause System.IndexOutOfRangeException

To Reproduce I've made a sample project, please give a look GeneticSharpTest.zip

Expected behavior Should not throw an exception

Version: 2.5.1

giacomelli commented 5 years ago

The error occurs inside the CreateChild method:

for (int i = 0; i < firstParent.Length && childGenesIndex < firstParent.Length; i++)
{
    AddChildGene(childGenes, ref childGenesIndex, firstParent.GetGene(i));
    AddChildGene(childGenes, ref childGenesIndex, secondParent.GetGene(i));
}

If childGenesIndex is in the last position and the first AddChildGene increment it, the IndexOutOfRangeException will happen in the second AddChildGene call.

I added a second check to fix the problem:

for (int i = 0; i < firstParent.Length && childGenesIndex < firstParent.Length; i++)
{
    AddChildGene(childGenes, ref childGenesIndex, firstParent.GetGene(i));

    // The childGenesIndes could be incremented by the previous AddChildGene call
    if (childGenesIndex < secondParent.Length)
        AddChildGene(childGenes, ref childGenesIndex, secondParent.GetGene(i));
}

A hotfix is on the way on to the AppVeyor, in a few minutes the 2.5.2 version will be available on NuGet.

Thanks for the bug report!