[11659] | 1 | using System;
|
---|
[11690] | 2 | using System;
|
---|
[11659] | 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;
|
---|
[11730] | 15 | private readonly IProblem problem;
|
---|
[11659] | 16 |
|
---|
[11730] | 17 | public RandomSearch(IProblem problem, Random random, int maxLen) {
|
---|
[11659] | 18 | this.maxLen = maxLen;
|
---|
[11730] | 19 | this.random = random;
|
---|
| 20 | this.problem = problem;
|
---|
[11659] | 21 | }
|
---|
| 22 |
|
---|
[11730] | 23 | public void Run(int maxIterations) {
|
---|
[11659] | 24 | double bestQuality = double.MinValue;
|
---|
| 25 | for (int i = 0; i < maxIterations; i++) {
|
---|
[11730] | 26 | var sentence = CreateSentence(problem.Grammar).ToString();
|
---|
[11732] | 27 | var quality = problem.Evaluate(sentence) / problem.BestKnownQuality(maxLen);
|
---|
[11659] | 28 | RaiseSolutionEvaluated(sentence, quality);
|
---|
| 29 |
|
---|
| 30 | if (quality > bestQuality) {
|
---|
| 31 | bestQuality = quality;
|
---|
| 32 | RaiseFoundNewBestSolution(sentence, quality);
|
---|
| 33 | }
|
---|
| 34 | }
|
---|
| 35 | }
|
---|
| 36 |
|
---|
[11730] | 37 | private Sequence CreateSentence(IGrammar grammar) {
|
---|
| 38 | var sentence = new Sequence(grammar.SentenceSymbol);
|
---|
[11659] | 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 | }
|
---|