Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11692 was 11690, checked in by gkronber, 10 years ago

#2283: added exhaustive BFS and DFS

File size: 1.6 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
16    public RandomSearch(int maxLen) {
17      this.maxLen = maxLen;
18      this.random = new Random(31415);
19    }
20
21    public void Run(IProblem problem, int maxIterations) {
22      double bestQuality = double.MinValue;
23      for (int i = 0; i < maxIterations; i++) {
24        var sentence = CreateSentence(problem.Grammar);
25        var quality = problem.Evaluate(sentence);
26        RaiseSolutionEvaluated(sentence, quality);
27
28        if (quality > bestQuality) {
29          bestQuality = quality;
30          RaiseFoundNewBestSolution(sentence, quality);
31        }
32      }
33    }
34
35    private string CreateSentence(IGrammar grammar) {
36      var sentence = grammar.SentenceSymbol.ToString();
37      return grammar.CompleteSentenceRandomly(random, sentence, maxLen);
38    }
39
40    private void RaiseSolutionEvaluated(string sentence, double quality) {
41      var handler = SolutionEvaluated;
42      if (handler != null) handler(sentence, quality);
43    }
44    private void RaiseFoundNewBestSolution(string sentence, double quality) {
45      var handler = FoundNewBestSolution;
46      if (handler != null) handler(sentence, quality);
47    }
48  }
49}
Note: See TracBrowser for help on using the repository browser.