source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization/RandomSearch.cs @ 11732

Last change on this file since 11732 was 11732, checked in by gkronber, 5 years ago

#2283: refactoring and bug fixes

File size: 1.7 KB
Line 
1using System;
2using System;
3using System.Collections.Generic;
4using System.Linq;
5using System.Text;
6using HeuristicLab.Problems.GrammaticalOptimization;
7
8namespace HeuristicLab.Algorithms.GrammaticalOptimization {
9  public class RandomSearch {
10    public event Action<string, double> FoundNewBestSolution;
11    public event Action<string, double> SolutionEvaluated;
12
13    private readonly int maxLen;
14    private readonly Random random;
15    private readonly IProblem problem;
16
17    public RandomSearch(IProblem problem, Random random, int maxLen) {
18      this.maxLen = maxLen;
19      this.random = random;
20      this.problem = problem;
21    }
22
23    public void Run(int maxIterations) {
24      double bestQuality = double.MinValue;
25      for (int i = 0; i < maxIterations; i++) {
26        var sentence = CreateSentence(problem.Grammar).ToString();
27        var quality = problem.Evaluate(sentence) / problem.BestKnownQuality(maxLen);
28        RaiseSolutionEvaluated(sentence, quality);
29
30        if (quality > bestQuality) {
31          bestQuality = quality;
32          RaiseFoundNewBestSolution(sentence, quality);
33        }
34      }
35    }
36
37    private Sequence CreateSentence(IGrammar grammar) {
38      var sentence = new Sequence(grammar.SentenceSymbol);
39      return grammar.CompleteSentenceRandomly(random, sentence, maxLen);
40    }
41
42    private void RaiseSolutionEvaluated(string sentence, double quality) {
43      var handler = SolutionEvaluated;
44      if (handler != null) handler(sentence, quality);
45    }
46    private void RaiseFoundNewBestSolution(string sentence, double quality) {
47      var handler = FoundNewBestSolution;
48      if (handler != null) handler(sentence, quality);
49    }
50  }
51}
Note: See TracBrowser for help on using the repository browser.