1 | using System;
|
---|
2 | using System;
|
---|
3 | using System.Collections.Generic;
|
---|
4 | using System.Linq;
|
---|
5 | using System.Text;
|
---|
6 | using HeuristicLab.Problems.GrammaticalOptimization;
|
---|
7 |
|
---|
8 | namespace 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 | }
|
---|