using System; using System; using System.Collections.Generic; using System.Linq; using System.Text; using HeuristicLab.Problems.GrammaticalOptimization; namespace HeuristicLab.Algorithms.GrammaticalOptimization { public class RandomSearch { public event Action FoundNewBestSolution; public event Action SolutionEvaluated; private readonly int maxLen; private readonly Random random; private readonly IProblem problem; public RandomSearch(IProblem problem, Random random, int maxLen) { this.maxLen = maxLen; this.random = random; this.problem = problem; } public void Run(int maxIterations) { double bestQuality = double.MinValue; for (int i = 0; i < maxIterations; i++) { var sentence = CreateSentence(problem.Grammar).ToString(); var quality = problem.Evaluate(sentence) / problem.BestKnownQuality(maxLen); RaiseSolutionEvaluated(sentence, quality); if (quality > bestQuality) { bestQuality = quality; RaiseFoundNewBestSolution(sentence, quality); } } } private Sequence CreateSentence(IGrammar grammar) { var sentence = new Sequence(grammar.SentenceSymbol); return grammar.CompleteSentenceRandomly(random, sentence, maxLen); } private void RaiseSolutionEvaluated(string sentence, double quality) { var handler = SolutionEvaluated; if (handler != null) handler(sentence, quality); } private void RaiseFoundNewBestSolution(string sentence, double quality) { var handler = FoundNewBestSolution; if (handler != null) handler(sentence, quality); } } }