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