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()} "; }
public void Simulate(int startTemperature, int boardSize, IChessboardGenerator generator, IFitnessCalculator calculator) { Fitness BestPossibleFitness = calculator.BestFitness; int tenPercent = startTemperature / 10; Chessboard currentBestChessboard = generator.Generate(boardSize); Temperature currentTemperature = new Temperature(startTemperature); Fitness currentBestFitness = calculator.WorstFitness; while (currentTemperature.IsNotZero && currentBestFitness.IsWorseThan(BestPossibleFitness)) { Chessboard chessboard = generator.Generate(boardSize); Fitness currentFitness = calculator.CalculateFitness(chessboard); if (currentFitness.IsBetterThan(currentBestFitness)) { currentBestFitness = currentFitness; currentBestChessboard = chessboard; currentTemperature.IncreaseBy(tenPercent); } else { currentTemperature.DecreaseBy(1); } } FinalChessboard = currentBestChessboard; Result = $@" -- Simulated Annealing Result -- Current Temperature: {currentTemperature.Value} Fitness: {calculator.CalculateFitness(FinalChessboard).Value} {FinalChessboard.ToString()} "; }