示例#1
0
        public double GetKnapsackFitness(Knapsack knapsack)
        {
            var totalWeight = (double)knapsack.GetTotalWeight(Packages);
            var totalValue  = (double)knapsack.GetTotalValue(Packages);

            var fitness = 0d;

            if (totalWeight <= _maxKnapsackWeight)
            {
                return(totalValue);
            }

            switch (PenaltyMethod)
            {
            case PenaltyMethod.Static:
                fitness = 0;
                break;

            case PenaltyMethod.Adaptive:
                double penalty = 1 / (totalWeight - _maxKnapsackWeight);
                fitness = totalValue * penalty - 1;
                break;
            }

            return(fitness);
        }
示例#2
0
        public Knapsack Crossover(Knapsack parent1, Knapsack parent2)
        {
            var random = RandomGenerator.Random.NextDouble();
            var child  = new Knapsack(_knapsackCapacity, _maxKnapsackWeight);

            if (random <= CrossoverRate)
            {
                var crossoverPoint = RandomGenerator.Random.Next(1, 20);
                var endPoint       = _knapsackCapacity - crossoverPoint;
                child.BitString = $"{parent1.BitString.Substring(0, crossoverPoint)}{parent2.BitString.Substring(crossoverPoint, endPoint)}";

                return(child);
            }

            return(GetKnapsackFitness(parent1) > GetKnapsackFitness(parent2) ? parent1 : parent2);
        }
示例#3
0
        public Knapsack Mutate(Knapsack candidate)
        {
            var bitString = "";

            foreach (var bit in candidate.BitString)
            {
                var random = RandomGenerator.Random.NextDouble();
                if (random <= MutationRate)
                {
                    bitString += bit == '1' ? '0' : '1';
                }
                else
                {
                    bitString += bit;
                }
            }

            candidate.BitString = bitString;
            return(candidate);
        }