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 | 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 | }
|
---|