Example #1
0
        public Tour CrossingOver(Tour that)
        {
            Tour child = new Tour(verticesNumber);

            bool[] verticeIsUsed = new bool[verticesNumber];

            for (int i = 0; i < verticesNumber; i++)
            {
                child.tourIndexes[i] = -1;
                verticeIsUsed[i]     = false;
            }

            int currentIndex = 0;

            for (int i = 0; i < verticesNumber; i++)
            {
                Tour parent1;
                Tour parent2;

                if (i % 2 == 0)
                {
                    parent1 = this;
                    parent2 = that;
                }
                else
                {
                    parent1 = that;
                    parent2 = this;
                }

                int linkFromParent1 = parent1.IndexAt(currentIndex);
                int linkFromParent2 = parent2.IndexAt(currentIndex);
                if (!verticeIsUsed[linkFromParent1] && child.tourIndexes[linkFromParent1] == -1 && linkFromParent1 != 0)
                {
                    verticeIsUsed[linkFromParent1]  = true;
                    child.tourIndexes[currentIndex] = linkFromParent1;
                    currentIndex = linkFromParent1;
                }
                else
                {
                    if (!verticeIsUsed[linkFromParent2] && child.tourIndexes[linkFromParent2] == -1 && linkFromParent2 != 0)
                    {
                        verticeIsUsed[linkFromParent2]  = true;
                        child.tourIndexes[currentIndex] = linkFromParent2;
                        currentIndex = linkFromParent2;
                    }
                    else
                    {
                        for (int j = 1; j < verticesNumber; j++)
                        {
                            if (!verticeIsUsed[j] && child.tourIndexes[j] == -1)
                            {
                                verticeIsUsed[j] = true;
                                child.tourIndexes[currentIndex] = j;
                                currentIndex = j;
                            }
                        }
                    }
                }
            }

            child.tourIndexes[currentIndex] = 0;

            return(child);
        }