Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11659 was 11659, checked in by gkronber, 8 years ago

#2283 initial import of implementation of grammatical optimization problem instances

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