Rev | Line | |
---|
[12098] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
| 3 | using System.Linq;
|
---|
| 4 | using HeuristicLab.Algorithms.MonteCarloTreeSearch.Base;
|
---|
| 5 | using HeuristicLab.Problems.GrammaticalOptimization;
|
---|
| 6 |
|
---|
| 7 | namespace HeuristicLab.Algorithms.MonteCarloTreeSearch.Simulation
|
---|
| 8 | {
|
---|
| 9 | public class RandomSimulation : ISimulation
|
---|
| 10 | {
|
---|
| 11 | private IProblem problem;
|
---|
| 12 | private IGrammar grammar;
|
---|
| 13 | private Random random;
|
---|
| 14 | private int maxLen;
|
---|
| 15 |
|
---|
| 16 | public RandomSimulation(IProblem problem, Random random, int maxLen)
|
---|
| 17 | {
|
---|
| 18 | this.problem = problem;
|
---|
| 19 | this.grammar = problem.Grammar;
|
---|
| 20 | this.random = random;
|
---|
| 21 | this.maxLen = maxLen;
|
---|
| 22 | }
|
---|
| 23 |
|
---|
| 24 | public double Simulate(TreeNode node)
|
---|
| 25 | {
|
---|
| 26 | Sequence sequence = new Sequence(node.phrase);
|
---|
| 27 | List<int> ntPositions = new List<int>();
|
---|
| 28 | while (!sequence.IsTerminal)
|
---|
| 29 | {
|
---|
| 30 | // select one random nt-symbol
|
---|
| 31 | ntPositions.Clear();
|
---|
| 32 | for (int i = 0; i < sequence.Length; i++)
|
---|
| 33 | {
|
---|
| 34 | if (grammar.IsNonTerminal(sequence[i]))
|
---|
| 35 | {
|
---|
| 36 | ntPositions.Add(i);
|
---|
| 37 | }
|
---|
| 38 | }
|
---|
| 39 | int ntSymbolIndex = ntPositions[random.Next(ntPositions.Count)];
|
---|
| 40 | char ntSymbol = sequence[ntSymbolIndex];
|
---|
| 41 |
|
---|
| 42 | // select one random alternative for nt-symbol
|
---|
| 43 | IEnumerable<Sequence> alternatives = grammar.GetAlternatives(ntSymbol);
|
---|
| 44 | Sequence alternative = alternatives.ElementAt(random.Next(alternatives.Count()));
|
---|
| 45 | if (sequence.Length + alternative.Length - 1 <= maxLen)
|
---|
| 46 | {
|
---|
| 47 | sequence.ReplaceAt(ntSymbolIndex, 1, alternative);
|
---|
| 48 | }
|
---|
| 49 | }
|
---|
| 50 | return problem.Evaluate(sequence.ToString());
|
---|
| 51 | }
|
---|
| 52 | }
|
---|
| 53 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.