Example #1
0
        static void Main(string[] args)
        {
            IntelligentRandom      intelligentRandom = new IntelligentRandom();
            BasicFitnessCalculator basicCalculator   = new BasicFitnessCalculator();

            var simulatedAnnealing = new SimulatedAnnealing();

            simulatedAnnealing.Simulate(
                startTemperature: 10000,
                boardSize: 10,
                generator: intelligentRandom,
                calculator: basicCalculator
                );
            Console.WriteLine(simulatedAnnealing.Result);

            var tabuSearch = new TabuSearch();

            tabuSearch.Simulate(
                maxTabuListCount: 1500,
                boardSize: 10,
                generator: intelligentRandom,
                calculator: basicCalculator
                );
            Console.WriteLine(tabuSearch.Result);
        }
Example #2
0
        public void Simulate(int maxTabuListCount, int boardSize,
                             IChessboardGenerator generator,
                             IFitnessCalculator calculator)
        {
            Fitness              BestPossibleFitness = calculator.BestFitness;
            IntelligentRandom    random = new IntelligentRandom();
            Chessboard           currentCentralPoint        = random.Generate(boardSize);
            Chessboard           currentBestSolution        = currentCentralPoint;
            HashSet <Chessboard> tabuList                   = new HashSet <Chessboard>();
            Fitness              currentBestSolutionFitness = calculator.WorstFitness;

            while (tabuList.Count < maxTabuListCount &&
                   currentBestSolutionFitness.IsWorseThan(BestPossibleFitness))
            {
                Chessboard bestCandidate = currentCentralPoint?
                                           .GetNeighbourhoodOf()
                                           .Except(tabuList)
                                           .OrderBy(ch => calculator.CalculateFitness(ch).Value)
                                           .FirstOrDefault();

                Fitness bestCandidateFitness = calculator.CalculateFitness(bestCandidate);
                currentBestSolutionFitness = calculator.CalculateFitness(currentBestSolution);

                currentCentralPoint = bestCandidate;
                if (bestCandidateFitness.IsBetterThan(currentBestSolutionFitness))
                {
                    currentBestSolution = bestCandidate;
                }

                tabuList.Add(bestCandidate);
            }

            FinalChessboard = currentBestSolution;
            Result          = $@"
-- Tabu Search Result --
Tabu List Count: {tabuList.Count}
Fitness: {calculator.CalculateFitness(FinalChessboard).Value}
{FinalChessboard.ToString()}
            ";
        }