Example #1
0
        public static KnapsackConfig MutateHalf(KnapsackConfig sack, Random rand)
        {
            KnapsackConfig mutatedSack      = new KnapsackConfig(sack);
            int            mutationPosition = rand.Next(itemsAmount);

            if (rand.Next() % 2 == 0)
            {
                for (var i = 0; i < itemsAmount / 2; i++)
                {
                    mutatedSack.swapValue(i);
                }
            }
            else
            {
                for (var i = itemsAmount / 2; i < itemsAmount; i++)
                {
                    mutatedSack.swapValue(i);
                }
            }
            if (!IsValid(mutatedSack))
            {
                return(MakeValid(mutatedSack));
            }
            return(mutatedSack);
        }
Example #2
0
        public static KnapsackConfig SinglePointMutation(KnapsackConfig sack, Random rand)
        {
            KnapsackConfig mutatedSack        = new KnapsackConfig(sack);//copy constructor
            int            mutationPosition   = rand.Next(itemsAmount);
            var            count              = 0;
            var            iterationsToResque = 100000;

            while (mutatedSack.Equals(sack) && count < iterationsToResque)//TODO - not mutate empty sack
            {
                mutatedSack.swapValue(mutationPosition);
                if (!IsValid(mutatedSack))//somehow unrealistic
                {
                    mutatedSack.swapValue(mutationPosition);
                    mutationPosition = rand.Next(itemsAmount);
                }
                count++;
            }
            if (count == iterationsToResque)
            {
                return(MakeValid(mutatedSack));
            }
            return(mutatedSack);
        }