using System; using System.Collections.Generic; using System.Linq; using HeuristicLab.Algorithms.MonteCarloTreeSearch.Base; using HeuristicLab.Problems.GrammaticalOptimization; namespace HeuristicLab.Algorithms.MonteCarloTreeSearch.Simulation { public class RandomSimulation : ISimulation { private IProblem problem; private IGrammar grammar; private Random random; private int maxLen; public RandomSimulation(IProblem problem, Random random, int maxLen) { this.problem = problem; this.grammar = problem.Grammar; this.random = random; this.maxLen = maxLen; } public double Simulate(TreeNode node) { Sequence sequence = new Sequence(node.phrase); List ntPositions = new List(); while (!sequence.IsTerminal) { // select one random nt-symbol ntPositions.Clear(); for (int i = 0; i < sequence.Length; i++) { if (grammar.IsNonTerminal(sequence[i])) { ntPositions.Add(i); } } int ntSymbolIndex = ntPositions[random.Next(ntPositions.Count)]; char ntSymbol = sequence[ntSymbolIndex]; // select one random alternative for nt-symbol IEnumerable alternatives = grammar.GetAlternatives(ntSymbol); Sequence alternative = alternatives.ElementAt(random.Next(alternatives.Count())); if (sequence.Length + alternative.Length - 1 <= maxLen) { sequence.ReplaceAt(ntSymbolIndex, 1, alternative); } } return problem.Evaluate(sequence.ToString()); } } }